开发者

How to increment div id with php for loop?

I have the following div. I would like to have mydiv1, mydiv2 and mydiv3. Is this possible to do?

Code:

<?php for($i =1; $i <3; $i++):?>
    <div id="mydiv<?php $i?>" style="float:left">
<?php endfor;?>开发者_高级运维


Remove the inner for loop and you will get only 3 divs.

if you want to assign id's in div dynamically try this:

$somearray = array(
        'animal'=>'cat',
        'place'=>'earth',
        'food'=>'orange'
);
$i=1;
foreach ($somearray as $k=>$v){
    echo '<div id="div'.$i.'">'. $v .'<div>';
    $i++;
}

In your code you are getting 9 elements because what you are doing is first loop through $somearray elements which is 3 times and inside that loop you again loop for 3 times using variable $i so 3*3=9. and you are getting 9 divs.


Use <?php echo $i; ?> instead of <?php $i?>.


Why do you have 9 elements? Because you're generating nine elements.

$somearray = array(
        'animal'=>'cat',
        'place'=>'earth',
        'food'=>'orange'
);

foreach ($somearray as $k=>$v){
    for($i=1;$i<=3;$i++){
    echo '<div id="div'.$i.'">'. $v .'<div>';
    }
}

Let me elaborate:

The above code block is equal to this set of codeblocks.

where $somearray value = 'animal'=>'cat' do this:

for($i=1;$i<=3;$i++){
echo '<div id="div'.$i.'">'. $v .'<div>';
}

and

where $somearray value = 'place'=>'earth' do this:

for($i=1;$i<=3;$i++){
echo '<div id="div'.$i.'">'. $v .'<div>';
}

and

where $somearray value = 'food'=>'orange' do this:

for($i=1;$i<=3;$i++){
echo '<div id="div'.$i.'">'. $v .'<div>';
}

All because of this:

foreach ($somearray as $k=>$v){
  ...
}


You don't need the inner for loop (3 x 3 = 9). You simply need a counter that you increment on each iteration of the outer loop:

<?php

$somearray = array(
        'animal'=>'cat',
        'place'=>'earth',
        'food'=>'orange'
);

$counter = 1;
foreach ($somearray as $k=>$v){
    echo '<div id="div'.$counter .'">'. $v .'<div>';
    $counter++;
}


<?php 
for($i =1; $i <3; $i++){
echo <<<CODE
<div id="mydiv$i" style="float:left;">
CODE;
}
?>


You need to give like,

<div id="mydiv<?php echo $i;?>" style="float:left">

it will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜