Can somebody just explain to me what this PHP code does?? Thanks?

  • Thread starter Thread starter stephen m
  • Start date Start date
S

stephen m

Guest
This is just a tenary.. Its the same as:

$value = 0;
if ( isset($contents[$item]) {
$value = $contents[$item] + 1;
} else {
$value = 1;
}

A tenary is just a nicer, more efficent way of writing it in this case. I remember it like this:

the ? means - if the last thing said is true then do it.. and the : I remember as if - screw it - go ahead and do this instead.
 
Just tell me like why the '?' is there and what it is performing...;

$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;

Thanks :D
 
It's usually called the ternary operator or the ? : operator, and it's a common feature of languages with C-style syntax, like C++, Java, PHP, C#, etc. It follows this form:

x ? y : z

x is a boolean expression. If it evaluates to true, then y is returned; otherwise, z is returned. So, in a simple example:

$msg = (x < 5) ? "x is less than 5" : "x is not less than 5";

If x is less than five, then $msg will contain "x is less than 5". If not, it will contain "x is not less than 5". This is exactly the same as:

if ( x < 5 ) {
$msg = "x is less than 5";
} else {
$msg = "x is not less than 5";
}

but it's a little cleaner and more compact. You never need to use this syntax, since it can always be re-written as an if-else block, but it saves time and most people find it a bit more readable.

Your code is checking to see if $contents[$item] exists (using the isset() function). If it does, it adds 1 to the existing value. If not, it inserts the value 1 there.
 
Back
Top