Question

In this php code, during a while loop, I was hoping to use later 3 variables called $menu_1, $menu_2, and $menu_3. Is this possible in PHP?

while($parent_row = mysql_fetch_array($parent_result)){
    $menu_ = "";
    $menu_ . $i = "\n\t$('#menu_" . $i . "').hover(function () {";
}
echo $menu_1;
echo $menu_2;
echo $menu_3;
Était-ce utile?

La solution

You can use curly brackets for that:

${'menu' . $i}

but I strongly advise you just to echo the stuff you need inside the loop.

Plus, mysql_* functions are deprecated - go either the PDO or the mysqli way please.

Autres conseils

Whenever somebody says "dynamic variables" it's a big red flag. You can do them but it's a bad idea 99% of the time. What you're probably looking for is an array. If you write:

$menus = array();
while($parent_row = mysql_fetch_array($parent_result)){
    $menus[$i] = "\n\t$('#menu_" . $i . "').hover(function () {";
}
echo $menus[1];
echo $menus[2];
echo $menus[3];

You'll get what you're after without delving into the maintenance headache & potential disaster that dynamic variable names would give you. You can also easily loop over $menus which makes things nice when you suddenly have 2, 4 or 40 different elements.

Yes you can. Just use brackets. Look at this example:

<?php

$one = 1;

$suffix_one = "_".$one;
$suffix_two = "_2";

$base_1 = "VALUE ONE";
$base_2 = "VALUE TWO";

echo ${"base".$suffix_one}." , ".${"base".$suffix_two};

?>

Result:

VALUE ONE , VALUE TWO

Obviously, like other users said, you'd better use arrays. But i answered anyway for your information.

Why not use arrays instead?

$menu[$i] = "\n\t$('#menu_" . $i . "').hover(function () {";
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top