Created
October 27, 2017 12:18
-
-
Save paulund/76299fcd0ffb95a46dc043f992899963 to your computer and use it in GitHub Desktop.
PHP7 Array Iteration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function loopThroughArrayErrors($array) | |
{ | |
foreach($array['values'] as $key => $value) | |
{ | |
echo $value; | |
} | |
} | |
function loopThroughArray($array) | |
{ | |
foreach($array['values'] ?? [] as $key => $value) | |
{ | |
echo $value; | |
} | |
} | |
/** | |
* This will error because the values index is undefined | |
*/ | |
$array = ['stuff']; | |
loopThroughArrayErrors( $array ); | |
/** | |
* This will no error as an empty array will be used in the foreach | |
*/ | |
$array = ['stuff']; | |
loopThroughArray( $array ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment