In this tutorial we're going to look into a look tip for dealing with PHP array iterations with PHP 7. When you're developing in PHP and need to iterate over an array you'll probably see something like this.
foreach($array['values'] as $value)
{
}
The problem with this is that you're assuming that the array will always have a key of values $array['values']
. If this isn't set PHP will error saying that values is not defined. This is where you'll see most people wrap this foreach around a isset or a !empty if statement.
if(isset($array['values']))
{
foreach($array['values'] as $value)
{
}
}
This will make sure that when the code reaches the array it will have all the data it needs to continue in the script. With PHP7 we can clean up this code by using the null coalesce operator ??
. The null coalesce operator allow us to wrap this isset if statement into a single line of code.
$value = $_GET['query'] ?? 'not set';
As you can see from the above code example we're using the ??
operator to check if the $_GET['query'] is set. If the querystring does have a query option then $value
will be set to the value in the querystring. If query is not in the query string then the $value
will be not set. Therefore we can use this inside the foreach to make sure we only loop through the array when values is set by using the below code.
foreach($array['values'] ?? [] as $key => $value)
{
echo $value;
}
Now if values is not set we will attempt to loop through an empty array and the foreach will be by-passed.