Last active
August 29, 2015 13:57
-
-
Save beporter/9814318 to your computer and use it in GitHub Desktop.
Handle PHP associative and indexed array in a single loop
This file contains hidden or 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 brian($i) { | |
foreach ($i as $value => $name) { | |
$value = (is_string($value) ? $value : $name); | |
echo '<option value="' . $value . '">' . $name . '</option>' . PHP_EOL; | |
} | |
} | |
//-------------------- | |
// Breaks if there is even a single element with an associative (string) key. | |
function gus($i) { | |
if( count( array_filter( array_keys( $i ), 'is_string' ) ) ) { | |
foreach( $i as $value => $name ) { | |
echo '<option value="' . $value . '">' . $name . '</option>' . PHP_EOL; | |
} | |
} else { | |
foreach( $i as $value ) { | |
echo '<option value="' . $value . '">' . $value . '</option>' . PHP_EOL; | |
} | |
} | |
} | |
//-------------------- | |
// At least this approach means you don't have to manage the output format in multiple places. | |
function gus2($i) { | |
if( count( array_filter( array_keys( $i ), 'is_string' ) ) ) { | |
foreach( $i as $value => $name ) { | |
gus2_helper($value, $name); | |
} | |
} else { | |
foreach( $i as $value ) { | |
gus2_helper($value); | |
} | |
} | |
} | |
function gus2_helper($value, $name = null) { | |
$name = (is_null($name) ? $value : $name); | |
echo '<option value="' . $value . '">' . $name . '</option>' . PHP_EOL; | |
} | |
// main() ----------------------- | |
$input = array( | |
'value1', | |
'key1' => 'value2', | |
); | |
echo "Brian:\n"; | |
brian($input); | |
echo "\nGus:\n"; | |
gus($input); | |
echo "\nGus 2:\n"; | |
gus2($input); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: