Jump to content

Archived

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

max100

Looping through variable names

Recommended Posts

Hi,

I am very new to PHP and wondered if someone could point me in the right direction...

I have 10 variables called $title1, $title2, $title3, $title4 ... etc
Each variable either contains the string 'open' or 'closed' and I wish to change all those which contain 'closed' to empty variables. I understand loops, but I'm not sure how to loop through each variable name easily. Would an array come into this?

Probably a simple answer, but as I say, I'm very new to this and any help would be very much appreciated.

Thank you.

Max100

Share this post


Link to post
Share on other sites
Use a for loop:
[code=php:0]<?php

$title1 = 'open';
$title2 = 'open';
$title3 = 'closed';
$title4 = 'open';
$title5 = 'closed';
$title6 = 'open';
$title7 = 'closed';
$title8 = 'closed';
$title9 = 'open';
$title10 = 'open';

for($i = 1; $i < 11; $i++)
{
    if(${'title'.$i} == 'closed')
    {
      ${'title'.$i} = null;
    }
}

for($i = 1; $i < 11; $i++)
{
    echo '$tile' .$i . ' = ' . ${'title'.$i} . '<br />';
}

?>[/code]

Share this post


Link to post
Share on other sites
Great stuff.
It was the variable name which was messing me up ... wasn't sure how to append the $i onto the $link, but now I see how to use the curly braces.

Many thanks, much appreciated.

Max100

Share this post


Link to post
Share on other sites

×

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.