0

Sorry if this sounds dumb or have been asked previously; it's not exactly about performance, more about "how does it work under the hood". So, what would be (if any) speed difference between:

if(!empty($a)) { $a = 'whatever';}

and

$a = ''; $a = 'whatever'; 

...where 'whatever' is not always a string, but anything, incl. function value return.
It's like very basic things have escaped me (or it's just a lack of sleep); please, feel free to crucify me and thank you in advance for replies.

yurg
  • 113
  • 1
  • 5
  • If you're talking about speed-difference, you're essentially talking about performance. The latter would *always* assign the value, while the first would only assign it if the variable is not already empty, so they are logically different too. – Qirel Apr 23 '17 at 11:49
  • @Qirel thank you for note; yet, skipping differences, which is faster? – yurg Apr 23 '17 at 11:53
  • Honestly, there's very little that is different with them in terms of speed - the second one would be `$a = 'whatever';` anyways, so the first assignment to empty is pointless. Like I said, they're logically different and do different things in the end, so you can't really compare them, it's like comparing apples to bananas. If you want to optimize your code, this isn't what you should be doing - optimize something that matters instead ;-) – Qirel Apr 23 '17 at 11:58
  • excuse me , but what's the logic behind your first statement ? – hassan Apr 23 '17 at 12:00
  • and the more performance the more speed. – hassan Apr 23 '17 at 12:00
  • @Qirel sorry, seems I'm not quite good in a questions asking, let me , please, try again. So, it is a lot of code and somewhere between the lines I've been doing ** if(!empty($a) { // do stuff... ** to prevent "undefined value" notices. Essentially, the result of ** $a = ''; $a = 'whatever' ** is the same (so first assignment is not exactly pointless here, it prevents php from throwing notices). So, have just thought, if one can substitutes another, any reason to continue using IF statement? Guess the question is totally pointless, yet just out of curiosity. – yurg Apr 23 '17 at 12:12
  • @hassan Have just added a comment, which extends my question, thank you for your note. – yurg Apr 23 '17 at 12:13
  • If the question is about preventing undefined variables, there's a question http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef which should answer that. – Qirel Apr 23 '17 at 12:14
  • @Qirel not exactly, yet thank you for pointing; you're probably right, should do more reading first. – yurg Apr 23 '17 at 12:15

1 Answers1

0

So, I did my homework (thanks Google and https://3v4l.org/) and here's the results (screen grabs speak for themselves):

Create an empty var first enter image description here

Check it with IF enter image description here

Thanks to all who has participated!

yurg
  • 113
  • 1
  • 5