Page 1 of 1
if ($newName)
Posted: 09 Nov 2015 11:15
by armsys
How to interpret ($newName)?
Does it mean if $newName has been defined or null?
Re: if ($newName)
Posted: 09 Nov 2015 11:17
by highend
It means that $newName does not contain an empty / or 0 value.
Re: if ($newName)
Posted: 09 Nov 2015 11:19
by armsys
highend wrote:It means that $newName does not contain an empty / or 0 value.
Got it. Thanks.
The "If ($newName)" can't be found in the Bible. Sorry.
Re: if ($newName)
Posted: 09 Nov 2015 11:35
by PeterH
But please remember: normal variables (but not Global or Perm) return their own name if uninitialized - so if($newname) will be true in this case!
Re: if ($newName)
Posted: 09 Nov 2015 12:00
by highend
It's a follow-up question from
http://www.xyplorer.com/xyfc/viewtopic.php?f=7&t=14945
and ofc that variable was initialized before checking for it

Re: if ($newName)
Posted: 09 Nov 2015 12:10
by armsys
highend wrote:and ofc that variable was initialized before checking for it

OK. Got it. Thanks.

Re: if ($newName)
Posted: 09 Nov 2015 12:22
by armsys
highend wrote:and ofc that variable was initialized before checking for it

After searching the entire Script Exchange, the "if ($newName)" appears to be Highend's signature XY command. It looks like that Highend is the inventor of "if ($newName)" trick. After experimenting with the "if ($newName)" for a while, nowI realize the following undocumented effects:
1. the condition will be TRUE if $newName is assigned with any values, eg, "ofc", 123,...etc.
2. the condition will be FALSE if $newName is NOT assigned with any values.
Thank you Highend.

Re: if ($newName)
Posted: 09 Nov 2015 12:30
by highend
2. and not with 0
I'm not the inventor of a check like that. It's used in all modern computer languages. Normally for boolean values (true / false) but it can be "abused" for content checking as well...
Re: if ($newName)
Posted: 09 Nov 2015 14:11
by PeterH
...or in short:
0 or "" is false
everything else is true
Re: if ($newName)
Posted: 09 Nov 2015 14:27
by armsys
Hi Highend & PeterH,
PeterH wrote:...or in short:
0 or "" is false
everything else is true
Thank you for your thorough follow-up.
Thank you for further crystal-clear clarification (CCC).
Yeah, I've been playing with for the last few hours:
$a = 0; if ($a) { echo "true"; }
$a = -0; if ($a) { echo "true"; }
$a = -1; if ($a) { echo "true"; }
$a = a; if ($a) { echo "true"; }
So far PeterH's code is the most compact while Highend is more expansive.
Very different coding styles!!
Re: if ($newName)
Posted: 09 Nov 2015 16:24
by TheQwerty
FYI, if performing this test in a place where you cannot be certain that $newName was initialized you should also make use of
isset:
Code: Select all
if (isset($newName) && $newName) { ... }
Generally though you will only need to worry about this when using dereferences, since both
global and
perm initialize new vars to empty strings.