Home > PHP, Tutorials > Oft-forgotten methods

Oft-forgotten methods

After reviewing some of my code, I found out I had been doing quite a lot of stuff in deprecated or just plain bad coding. The methods / functions described are PHP examples only.

Ternary Operator

Huh what does that do?!

 
$a = ($b >= 0) ? "b is positive" : "b is negative";

The basic markup of this 'method' is as follows:

$variable = (expression) ? "value if true" : "value if not";

So the example above would set $a to "b is positive" if ($b ?= 0) and would set it to "b is negative" if $b < 0.

So that means it's shorthand for:

 
if ($b > 0)
$a = "b is positive";
else
$a = "b is negative";

Another way I've seen myself do something similar is explained by the following code:

 
$a = "b is negative";
if ($b >= 0) $a = "b is positive"

Comparison operators

Everybody knows about using a double equals sign to compare two values. But have you ever heard of the triple-=? The triple equals-sign is to compare the values AND the types of the variables, cough:

 
if ("1" == true) echo '1 == true'; // Outputs 1 == true
if ("1" === true) echo '1 === true'; // Not true
if ("1" === 1) echo '"1" === 1'; // Not true

I think you understand ;)

Popularity: 7% [?]

PHP, Tutorials

  1. No comments yet.
  1. No trackbacks yet.