开发者

php loop statement question

I'm wondering if it is possible to loop a vari开发者_开发技巧able within a variable? Here is something I want to setup:

$var1 = Benjamin
$var2 = George
$var3 = Abraham

and probably echo out something like

<li>Benjamin</li>
<li>George</li>
<li>Abraham</li>

but I want to know, if I want to add $var4 = ..., $var5 = ..., is there a way I can do this all in a loop? I'm thinking having an empty() function that'll loop the variable names/numbers until reaches the first empty variable?


You could store them in an array.

$names = array('Mike', 'Jim', 'Tom', 'Stacy');

foreach($names as $name){
  echo $name;
}

As seen here: http://www.ideone.com/f7Ce7


In PHP you can do this:

    $var1 = "foo";
    $var2 = "bar";

    $name = "var1";
    $i=1;
    while( !is_null( $$name ) ) {
            echo '<li>' . $$name . '</li>';
            $i++;
            $name = "var$i";
    }

but a better solution may be using an array and a foreach


This sounds like you want to use arrays and foreach. Am I missing something?

$presidents = array(
  'Benjamin', 'George', 'Abraham'
);

foreach($presidents as $pres) {
 echo "$pres\n";
}


$var=array('Benjamin', 'George', 'Abraham');

foreach ($var as $name){
echo $name;
}


A better solution would be arrays. define it as: $names = array(0=>"Benjamin",1=>"George",2=>"Abraham");

Then loop through it with:

foreach ($names as $id=>$name)
{
    echo $name;
}

Then reference a name with $names[0], if you want to add another use $names[] = 'William'; Look up more information at:http://php.net/manual/en/language.types.array.php


This solution doesn't require the use of an array.

$var1 = 'Benjamin';
$var2 = 'George';
$var3 = 'Abraham';
//add as many variables as you want

$i = 0;
$currentVariable = 'var'.$i;
while (isset($$currentVariable)) {
    //process variable
    echo $$currentVariable;
    $i++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜