Jump to content

Looping through variable names


max100

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
Link to comment
https://forums.phpfreaks.com/topic/18992-looping-through-variable-names/
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]

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.