Paul
Paul

Reputation: 633

Repeat var with dynamic value PHP

I've a certain amount of posts, each post contains a modal (sort of a popup) the HTML of this modal is in the $html[] var. The code below works well except as you can see it is not dynamic.

What i've tried:

$post_count = [1,2,3,4,5,6,7,8,9,10,11,12]; // i've to mannualy add a number according to the number of posts
$counter = 1;
foreach($number_of_modals as $modal){
    echo $html[$counter];
    $counter++;
}

Explanation of what i need to accomplish

$post_count; // if this val is 3 for example

echo $html[1];
echo $html[2];
echo $html[3];

Upvotes: 1

Views: 77

Answers (2)

ag0702
ag0702

Reputation: 381

Can you try this one?

foreach($number_of_modals as $key => $modal){
    echo $html[$key];
}

Since you haven't given the structure of $number_of_modals array, I assumed it's like the $html array

$modal = array('1', 'abc', 'etc');

Which translates to $modal = array(0 => '1', 1 => 'abc', 2 => 'etc');

In that foreach each $key corresponds to 0,1,2 which gives the $counter you are looking for.

Upvotes: 1

cyber_rookie
cyber_rookie

Reputation: 665

As Paul suggested, use either a for loop, or a while loop:

$post_count = 3;
$counter = 0;
while ($counter <= $post_count) {
    echo $html[$counter];
    $counter++;
}

Upvotes: 2

Related Questions