Skip to content

Instantly share code, notes, and snippets.

@paulund
Created October 27, 2017 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulund/76299fcd0ffb95a46dc043f992899963 to your computer and use it in GitHub Desktop.
Save paulund/76299fcd0ffb95a46dc043f992899963 to your computer and use it in GitHub Desktop.
PHP7 Array Iteration
<?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