Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop with two arrays [duplicate]

Tags:

arrays

php

I want to generate a selectbox using two arrays, one containing option-value and option-name and one containing data-value for the option

For example:

"arra1"  => array("1" => "orange", "2" => "banana", "3" => "apple"),
"data-array"  => array("first" , "second" , "third"),

and result must be

foreach( ??? ) {

<option value=1 data-value="first">orange</option>
<option value=2 data-value="second">banana</option>
<option value=3 data-value="third">apple</option>

}

Suggestions? Thanks

like image 278
FireFoxII Avatar asked Mar 03 '26 10:03

FireFoxII


1 Answers

Use PHP's array_values function to get both array with same indexing, then do the foreach:

$data = [
    "arra1"  => array("1" => "orange", "2" => "banana", "3" => "apple"),
    "data-array"  => array("first" , "second" , "third")
];

$labels = array_values($data["arra1"]);
$values = array_values($data["data-array"]);

foreach($labels as $index => $value) {
    $optionValue = $index+1;
    echo "<option value={$optionValue} data-value='{$values[$index]}'>{$labels[$index]}</option>";
}
like image 133
Elijah Avatar answered Mar 04 '26 23:03

Elijah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!