Skip to content

Instantly share code, notes, and snippets.

@joeljerushan
Last active April 30, 2021 17:02
Show Gist options
  • Save joeljerushan/d1b43e297df520349d61c0723d23164e to your computer and use it in GitHub Desktop.
Save joeljerushan/d1b43e297df520349d61c0723d23164e to your computer and use it in GitHub Desktop.
Set Selected with PHP without Javascript - Adding “selected” attribute to the selected option in PHP
<select>
<?php
//init array with key value pairs
$purchase_type = array(
'1' => 'White Rice',
'2' => 'Red Rice',
'3' => 'Wheat',
'4' => 'Packets',
'5' => 'Firewood'
);
foreach($purchase_type as $key => $single) {
//echo <option value="YOUR_VALUE
echo "<option value=".$key;
//if $YOUR_RETURN_VALUE matches our key echo selected
if($YOUR_RETURN_VALUE == $key){ echo " selected"; }
//option open in line 14 close bracket here
echo '>';
//print your value
echo $single;
//close option
echo "</option>";
}
?>
</select>
<!--check explain here - https://goo.gl/DtRGH7 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment