Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP speed: what is faster? if (isset ($foo)) OR if ($foo==true) [closed]

I am just trying to optimize my code. I need to prefill a form with data from a database, and I need to check if the variable exist to fill the text box (I don't like the @ error hiding). The form is really long, then I need to check multiple times if the variables exist.

What is faster of the following two?

  • if (isset ($item))
  • if ($item_exists==true)

Or even

  • if ($item_exists===true)
like image 972
earlyriser Avatar asked Mar 05 '10 20:03

earlyriser


People also ask

Is In_array slow?

PHP's in_array() function is really slow.

What is if isset ($_ POST submit )) in PHP?

isset( $_POST['submit'] ) : This line checks if the form is submitted using the isset() function, but works only if the form input type submit has a name attribute (name=”submit”).

What does isset () function do in PHP?

Definition and Usage. The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

Does PHP empty check Isset?

The isset() and ! empty() functions are similar and both will return the same results. But the only difference is ! empty() function will not generate any warning or e-notice when the variable does not exists.


2 Answers

With a for loop repeating it 10000000 times the same script took:

  • if (isset ($item)) 2.25843787193
  • if ($item_exists==true) 6.25483512878
  • if ($item_exists===true) 5.99481105804

So I can tell isset surely is faster.

like image 122
Marcx Avatar answered Sep 29 '22 13:09

Marcx


In this case you shouldn’t ask about performance but about correctness first. Because isset does not behave like a boolean convertion and comparison to true (see type comparison table). Especially the values "" (empty string), array() (empty array), false, 0, and "0" (0 as a string) are handled differently.

like image 37
Gumbo Avatar answered Sep 29 '22 12:09

Gumbo