teslasimus
teslasimus

Reputation: 1298

php: print variables in for loop

I hvae three variables,

$title_1 $title_2 $title_3

how can i print them in for loop?

what i've tried:

$number = 3;
    for($i=0;$i<$number;$i++){
            echo "$title_($i+1)";
    }

Upvotes: 1

Views: 1725

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173552

Don't meddle with these things; use an array for this stuff.

$titles = array('first title', 'second title', 'third title');

foreach ($titles as $title) {
    echo $title;
}

Upvotes: 5

BnW
BnW

Reputation: 602

This should work, haven't tested

for($i=1;$i<=$number;$i++){
        echo ${"title_$i"};
}

Upvotes: 5

cypher
cypher

Reputation: 6992

You can do this:

for($i = 0; $i < $number; $i++) {
    $var = "title_".$i;
    echo $$var;
}

But I wouldn't. This is really, REALLY bad design. Use arrays.

Upvotes: 4

Related Questions