1

I got this array:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => tomato
        )

    [1] => Array
        (
            [id] => 2
            [name] => carrot
        )

    [2] => Array
        (
            [id] => 3
            [name] => apple
        )

)

I want to print each key/value pair in an HTML form, like so:

<select>
    <option value="1">tomato</option>
    <option value="2">carrot</option>
    <option value="3">apple</option>
</select>

So, I'm using a foreach loop to iterate over the three items in the outer array and then try to print the items in the inner array on a single line. I'm stuck with the last bit. The closest I've got so far is this:

foreach ($food_opts as $key => $value) {
    foreach ($value as $k => $v) {
        echo '<pre>' . $v . '</pre>';
    }
}

This retrieves the data I need but not in a usable format:

1
tomato
2
carrot
3
apple

In short, how do you target individual items in an inner array? Something like:

foreach ($food_opts as $key => $value) {
    foreach ($value as $k => $v) {
        echo '<pre>' . $v[0] . ' - ' . $v[1] . '</pre>';
    }
}

I understand why the above code doesn't work but can't figure out how to get the data how I want it.

0

2 Answers 2

5

You don't need a nested foreach here. Just do:

foreach ($food_opts as $key => $arr) {
    echo '<option value="'.$arr['id'].'">'.$arr['name'].'</option>', PHP_EOL;
}

Or, you can use printf() for a more cleaner approach:

foreach ($food_opts as $key => $arr) {
    printf('<option value="%s">%s</option>', $arr['id'], $arr['name']).PHP_EOL;
}

The printf() family of functions uses % character as a placeholder. %s means "take the next argument and print it as a string". Similarly, %d means "take the next argument and print it as an int".

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much - yes, that makes sense. I've accepted your answer as it's more complete than Fabio's.
3

You need only one foreach loop to have all details available, you can then call them using variable assigned in the loop and keys in the scopes as follow

echo '<select>';
foreach ($food_opts as $value)
{
    echo '<option value="'.$value['id'].'">'.$value['name'].'</option>';
}
echo '</select>';

2 Comments

Many thanks - works a treat. I tried accepting both your answer and Amal Murali's but see I can only accept a single answer ;(.
It's ok, it's a pleasure to help people

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.