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
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

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.