user2212461
user2212461

Reputation: 3253

Why does this return empty strings?

I want to access the values of an associative array in PHP. I populate the array using the following loop in PHP:

$db = array("a","b","c");
foreach ($db as $q) {
    $$q = 'value';
}

This version prints the correct values

foreach ($db as $q) {
    echo '<li>'; echo $$q; echo '</li>';
}
\\THIS GIVES ME THE CORRECT OUTPUT <li>value</li><li>value</li><li>value</li>

But I want to access the values through their index

$num = count($db);
for ($i = 0; $i < $num; $i++) {
    echo '<li>'; echo $$db[$i]; echo '</li>';
}
\\\\THIS GIVES ME THE WRONG OUTPUT (EMPTY STRINGS <li></li><li></li><li></li>

What is going wrong in the second version? How can I access the values in this associative array through an index correctly?

Upvotes: 1

Views: 45

Answers (2)

Jos&#233; Carlos
Jos&#233; Carlos

Reputation: 91

You are trying to do something quite strange, anyway the solution to your problem are braces: { }

$num = count($db);
for ($i = 0; $i < $num; $i++) {
    echo '<li>'; echo ${$db[$i]}; echo '</li>';
}

Look how braces are resolving the ambiguity, since without them, php wouldn't know if you were referring to ${$db}[$i] or ${$db[$i]}

Upvotes: 1

Aloso
Aloso

Reputation: 5387

    echo '<li>'; echo $$db[$i]; echo '</li>';

In this line is one $ too much. Write:

    echo '<li>'; echo $db[$i]; echo '</li>';

This should do the trick.

PS: You don't have to write echo everytime. Use string concatenation:

    echo '<li>' . $db[$i] . '</li>';

Upvotes: 1

Related Questions