What do these do?
i keep seeing examples of these being used like here for example:
$exclude_boards = empty($exclude_boards) ? array() : $exclude_boards;
What is it doing?
What do these do?
i keep seeing examples of these being used like here for example:
$exclude_boards = empty($exclude_boards) ? array() : $exclude_boards;
What is it doing?
It's the ternary operator and is a shorthand way of doing a sort of if/else comparison. If the value before the "?" evaluates as TRUE, then the value after the "?" is used, else the value after the ":" is used. So these two chunks of code are functionally equivalent:
$result = ($var == 1) ? "one" : "something else";
if($var == 1)
{
$result = "one";
}
else
{
$result = "something else";
}
But in the example that i provided, there is no if() the whole thing looks like it is in a variable how would you then use it.
you cant write if($result) becsuse that would embed an if inside an ifs condition?
doesn't need an if...
<?php
$var = 1;
$result = ($var == 1) ? "one" : "something else";
echo $result;
?>
The above will echo: "one"
If you change $var = 1 to $var = 2, then the above will echo: "something else"
In terms of your original example...
$exclude_boards = empty($exclude_boards) ? array() : $exclude_boards;
...it's saying that if empty($exclude_boards) evaluates as true, then initialize $exclude_boards as an empty array, otherwise set it equal to its current value. Or in if/else code:
if(empty($exclude_boards)) // if $exclude_boards is not set or has an "empty" value
{
$exclude_boards = array(); // initialize it as an empty array
}
else
{
$exclude_boards = $exclude_boards; // use its current value
}
I doubt that I would have used the ternary operator in this situation. I suspect I would just have done something like:
if(!isset($exclude_boards))
{
$exclude_boards = array();
}
Or, if it's important that $exclude_boards be and array and there's any possibility that it could be set as something else:
if(!isset($exclude_boards) or !is_array($exclude_boards))
{
$exclude_boards = array();
}