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