Jump to content


Photo

Looping through variable names


  • Please log in to reply
2 replies to this topic

#1 max100

max100
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 29 August 2006 - 09:47 AM

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

#2 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 29 August 2006 - 09:56 AM

Use a for loop:
<?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 />';
}

?>


#3 max100

max100
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 29 August 2006 - 10:00 AM

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




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users