Jump to content

Looping through variables?


TJMAudio

Recommended Posts

I have a lot of variables that will either be 1 or 0.  I want to loop through them, putting all that equal 1 into a list.. it would look something like this:

 

<ul>
<li>$var1</li>
<li>$var2</li>
</ul>

And so on.

 

Is there any way of doing this?  All of the variables have different names, which is the problem I am having when coming up with this.

Link to comment
https://forums.phpfreaks.com/topic/107559-looping-through-variables/
Share on other sites

Well, part of your post makes no sense. If you put the variables as list items where the variables equal 1, then you will just have a list of 1's. Do you want the variable name as the list item?

 

I would suggest changing the variables to array elements.

 

<?php

$vars['var1'] = 0;
$vars['var2'] = 1;
$vars['var3'] = 0;
$vars['var4'] = 1;

echo "<ul>";

foreach ($vars as $varname => $varValue) {
  if ($varValue==1) {
    echo "<li>$varName</li>";
  }
}

echo "</ul>";
?>

 

The output would look like this:

  • var2
  • var4

use an array to hold your variables,

 

<?php
$arr = array("foo" => 1, "boo" => 0, "banana" => 0, "apple" => 1);

$output = "<ul>";
foreach($arr as $key => $val)
{
    if($val == 1)
    {
        $output .= "<li>{$key}</li>\n";
    }
}
echo $output."</ul>";

?>

 

outputs

 * foo
* apple

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.