Comparison operator or isset ()?

1

I'm developing an application for lotteries, where each game generated passes N filters before the numbers are shown. The tens are chosen, passed via $_POST to a php file that will do the rest.

In it I had a code basically like this:

foreach ($jogos_gerados as $jogos) {
    if ($_POST['filtro_1'] == 'on') {
        // Procedimentos do filtro
    }
    if ($_POST['filtro_2'] == 'on') {
        // Procedimentos do filtro
    }
    // E assim se repetia por mais 120 filtros
}

Well, it turns out that for the treatment of approximately 150 thousand bets I was having a very long processing time, even when I was not activating the $_POST['filtro_X'] == 'off' filters. So I decided to change everything this way:

foreach ($jogos_gerados as $jogos) {
    if (isset($_POST['filtro_1'])) {
        // Procedimentos do filtro
    }
    if (isset($_POST['filtro_2'])) {
        // Procedimentos do filtro
    }
    // E assim se repete por mais 120 filtros
}

And the time fell drastically to < 5s. What I'm curious to know is why this difference is so great between isset() and a comparison operator. Since in my view, both one and the other have to be checked if it exists to enter the filter ( TRUE to isset() and ON to the comparison operator).

    
asked by anonymous 20.12.2017 / 01:46

3 answers

5

The function% isset() and the comparison of values are different things, they do different things and their use is not exclusive to each other. isset() checks whether a variable is defined in the current scope, returning true when it is, regardless of the value; already the == operator compares the value of the variable and not if it is defined. In fact, the == operator even generates an error when the variable is not defined.

That is, you use isset() when you want to check if a variable is set and the == operator to check the value. In general, the two are used concomitantly, because before checking the value you should check whether it is set.

Just to highlight my comment, if you need to do more than 100 checks on your program, it's a good sign that you'll need to refactor it. Apparently you are sending the values of the filters as on or off and this does not make much sense. You could only send through the request the filters that are active and thus scroll through the list normally in $_POST with foreach . If this request is coming from HTML, these fields could possibly be checkbox , not radio or any other.

I will not comment on the difference in execution times between the two because it makes no sense to compare different things.

[1] isset() is actually a language constructor, not a function, and for PHP there are considerations to be made.     

20.12.2017 / 02:03
3
% is only to check if a variable or key exists within an array or isset , it is important to note that if the variable has the value stdObject it will also return false, then as examples:

<?php
$foo = 1;
$bar = 2;
$baz = null;

var_dump(isset($foo)); //Retorna true
var_dump(isset($bar)); //Retorna true
var_dump(isset($baz)); // Retorna false
var_dump(isset($naodeclarada)); // Retorna false

Example use with an array:

<?php
$foo = array(
    'bar' => array(
        'baz' => 1
    )
);

var_dump(isset($foo['bar']['baz'])); //Retorna true
var_dump(isset($foo['bar']['baz']['teste'])); //Retorna false

It would look like with NULL :

<?php
$foo = new stdClass;
$foo->baz = new stdClass;
$foo->baz->bar = 1;

var_dump(isset($foo->baz->bar)); //Retorna true
var_dump(isset($foo->baz->bar->teste)); //Retorna false

It is also important to note that stdClass can be used to check multiple values at the same time:

if (isset($_POST['foo'], $_POST['baz'], $_POST['bar'])) {
    //Executa
}

It would be the same as:

if (isset($_POST['foo']) && isset($_POST['baz']) && isset($_POST['bar'])) {
    //Executa
}

Note that variables in PHP with string value can work similar to arrays, for example:

$foo = 'abc';

var_dump($foo{1}); //Irá exibir "a"
var_dump($foo{2}); //Irá exibir "b"
var_dump($foo{3}); //Irá exibir "c"

In other words, to check if a variable has content, we usually use isset , which would look like this:

if (!empty($_POST['foo']) && !empty($_POST['baz']) && !empty($_POST['bar'])) {
    //Executa
}

How different from !empty will check if the variable is empty, however you might be able to do this:

if (isset($_POST['foo']{1}, $_POST['baz']{1}, $_POST['bar']{1})) {
    //Executa
}

What would make it much easier, but of course it is important to note that isset does much more than check for empty strings, so that it considers a variable to be empty may contain the following types of values:

  • empty (an empty string)
  • "" (when an integer equal to zero)
  • 0 (zero as string)
  • "0"
  • NULL
  • FALSE (an empty array)
  • array() (When a variable is declared in a class but has no value since it is NULL)

As I explained in link , that is public $var; may have more uses than empty will be able to use both as needed.

Now about comparing with isset it is important to note that if you do not have == or isset to check before it is likely that if empty no error_reporting is set to php.ini or E_NOTICE it will issue If you are in a folder with E_ALL (or any type other than POST) try to do this:

<?php
if ($_POST['foo']) {

}

Or:

$foo = $_POST['foo'];

The following message will be displayed:

  

Notice: Undefined index: foo in page.php

The message means that the super-global POST exists, but the GET (refers to the key) called index does not exist.

So for your specific code maybe the ideal would look something like this:

foreach ($jogos_gerados as $jogos) {
    //Checa se tem no minimo 2 caracteres e se é "on"
    if (isset($_POST['filtro_1']{2}) && $_POST['filtro_1'] == 'on') {
        // Procedimentos do filtro
    }

    //Checa se tem no minimo 2 caracteres e se é "on"
    if (isset($_POST['filtro_2']{2}) && $_POST['filtro_2'] == 'on') {
        // Procedimentos do filtro
    }
}

However being inside a loop, which is the foreach, I think multiple checks are unnecessary, you could optimize performance and even writing, could do something like:

function getFilters()
{
     $filters = array();

     //O 200 aqui é a quantidade possivel de filtros que você terá, pode editar
     for ($i = 1; $i <= 200; $i++) {
         $key = 'filtro_' . $i;

         //Faz uma comparação "inline" e salva no array
         $filters[$i] = isset($_POST[$key]{2}) && $_POST[$key] == 'on';
     }

     return $filters; //Retorna o array
}

//Pega os filtros
$filtros = getFilters(); //Irá retornar algo como array( 1 => true, 2 => false, ...)

foreach ($jogos_gerados as $jogos) {
    //Não precisará de isset, pois existe, só que é false ou true dependo do valor de filtro_1
    if ($filtro[1]) {
        // Procedimentos do filtro
    }

    //Não precisará de isset, pois existe, só que é false ou true dependo do valor de filtro_2
    if ($filtro[2]) {
        // Procedimentos do filtro
    }
}
    
20.12.2017 / 02:37
1

The isset () returns a Boolean value, true , or < in> false , that is, check whether the variable exists or not.

Verifying that the variable has a value set with == is more cumbersome for the server, as it should not only receive the POST, but also verify that its value is as expected. In%%, the server performs only 1 step, true or false .

The sensible performance improvement in your application is because PHP does not need to check if the value is "on", "off" or anything.

    
20.12.2017 / 02:02