Skip to content

Instantly share code, notes, and snippets.

@Mosharush
Last active August 9, 2017 23:23
Show Gist options
  • Save Mosharush/d8ce27de93695ff9ceb6f339be18c92b to your computer and use it in GitHub Desktop.
Save Mosharush/d8ce27de93695ff9ceb6f339be18c92b to your computer and use it in GitHub Desktop.
Format php array to HTML select tag
<?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