Marlon
Marlon

Reputation: 111

How do you use PHP to echo a number in increments?

I'm trying to design some elements that require less maintenance. With this process, I've been trying to figure out how to increase a number incrementally for each div on a page. Right now I'm using the 'foreach' construct to try this.

For example: One div would have, "Issue No. 1" another div would have text that reads, "Issue No. 2" etc.

for ($issNo = 1; $issNo <= 5; $issNo++) {
    echo $ContrHeadline = '<h1 class="cont-heading">Issue No. ' . $issNo . ' Winter 2016</h1>';
}

I think I am close. Right now, the above code is outputting that variable five times. I understand why, I just can't figure out how to split up the output, and echo it under various divs.

Below is the desired output.

Issue No. 1
~More content~

Issue No. 2
~More content~

Issue No. 3
~More content~

Issue No. 4
~More content~

Issue No. 5
~More content~

Right now I just have

Issue No. 1
Issue No. 2
Issue No. 3
Issue No. 4
Issue No. 5

I cannot separate the output. All of it is echoed all at once, therefore, I can't add content under each heading. I was hoping there was someway that I could store variables in an array, and assign each heading a variable with a different number increment.

$issNo = array("1","2","3","4","5");
foreach ($issNo as $issNo) {
    echo $ContrHeadline = '<h1 class="cont-heading">Issue No. ' . $issNo . ' Winter 2016</h1>';
}

echo $ContrHeadline;

After 'echo $ContrHeadline;' Should be separate code underneath, then another instance of 'echo $ContrHeadline' with the next increment of 'Issue No.'

Upvotes: 0

Views: 1292

Answers (2)

Ice76
Ice76

Reputation: 1130

Still not exactly sure why you dont put more infomation in the block the loop runs, but I think this is what you are going for:

    $issNo = array("1","2","3","4","5");
    foreach($issNo as $no) {
        echo '<div id="content' . $no . '">;
        echo '<h1 class="cont-heading">Issue No. ' . $no . ' Winter 2016</h1>';
        echo '~More Content';
        echo '</div><br />';
    }
    echo $ContrHeadline;

Upvotes: 2

miken32
miken32

Reputation: 42711

"I was hoping there was someway that I could store variables in an array, and assign each heading a variable."

Ok, so why not do that?

for ($issNo = 1; $issNo <= 5; $issNo++) {
    $ContrHeadlines[$issNo] = "<h1 class='cont-heading'>Issue No. $issNo</h1>";
}
// now do stuff like this:
echo $ContrHeadlines[1];
echo $ContrHeadlines[2];

Upvotes: 1

Related Questions