Last active
August 9, 2017 23:23
-
-
Save Mosharush/d8ce27de93695ff9ceb6f339be18c92b to your computer and use it in GitHub Desktop.
Format php array to HTML select tag
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 array2select( $name, $array, $assoc = false, $selected = null, $addArray = null ) { | |
if( isset( $addArray ) && is_array( $addArray ) ) { | |
$array = $addArray + $array; | |
} | |
if( ! $assoc ) { | |
$select = '<select name="' . $name . '"><option>' . implode( '</option><option>', $array ) . '</option></select>'; | |
if( isset( $selected ) ) { | |
$select = str_replace( '<option>' . $selected, '<option selected="selected">' . $selected, $select ); | |
} | |
return $select; | |
} | |
$select = '<select name="' . $name . '">' . PHP_EOL; | |
foreach ( $array as $key => $val ) { | |
$selectMe = isset( $selected ) && $selected == $key ? ' selected="selected"' : ''; | |
$select .= '<option' . $selectMe . ' value="' . $key . '">' . $val . '</option>' . PHP_EOL; | |
} | |
$select .= '</select>'; | |
return $select; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment