Skip to content

Instantly share code, notes, and snippets.

@beporter
Last active August 29, 2015 13:57
Show Gist options
  • Save beporter/9814318 to your computer and use it in GitHub Desktop.
Save beporter/9814318 to your computer and use it in GitHub Desktop.
Handle PHP associative and indexed array in a single loop
<?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);
@beporter
Copy link
Author

Output:

Brian:
<option value="value1">value1</option>
<option value="key1">value2</option>

Gus:
<option value="0">value1</option>
<option value="key1">value2</option>

Gus 2:
<option value="0">value1</option>
<option value="key1">value2</option>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment