How to increment div id with php for loop? - php

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.

Related

How to remove the last comma from foreach loop?

I am trying to remove the last comma(,) from foreach loop in php with the following code
<?php
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
?>
<?php echo $tag_name; ?> ,
<?php }
?>
Right I am getting result like
Hello, How, sam,
But i wants to remove the last comma
By placing the HTML in a simple string variable and then using rtrim() on the resulting string before outputting it this should remove the final , from the string
<?php
$out = '';
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
// move inside loop and amend to place in a simple string var
$out .= '' . $tag_name . ',';
?>
echo rtrim($out, ',');
You can also use the following code -
<?php
$numItems = count($snippet_tags);
$i = 0;
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
?>
if(++$i === $numItems)
echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a>";
else echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a> ,";
<?php
}
?>

PHP - How to use a div to wrap all items Inside a foreach loop

I have been scratching my head for half hour now trying to figure this out
I have a wrapper div inside a foreach loop and I'm trying to force it to echo one and not duplicate
foreach ($apples as $apple) {
//echo only once bellow
<div class="Wrapper">
//echo only once Above
echo $apple;
//echo only once bellow
</div>
//echo only once Above
}
I do not wish to move my Wrapper div outside the foreach, It is very important for the div to be inside the foreach and to be without duplicates.
You didn't mention but If you need to put Wrapper div only if you have any count in $apples variable then simply check with if(count($apples)) and then put Wrapper
<?php
if(count($apples)){
echo '<div class="Wrapper">';
foreach ($apples as $apple) {
echo $apple;
}
echo '</div>';
}
?>
Note: I know this is not good way to write but as per his condition I am suggesting this code.
I don't know why you don't want to put div outside foreach loop but anyway you can use the following code to achieve that...
<?php
foreach ($apples as $apple) {
static $i = 0;
if ($i == 0) {
echo "<div class='Wrapper'>";
}
echo $apple;
$i++;
if ($i == count($apples)){
echo "</div>";
}
}
?>
Maybe this will help since you want to keep it inside foreach loop
$numItems = count($arr);
$i = 0;
foreach($arr as $ar) {
$i = $i+1;
if ($i == 1) {
echo '<div class="class">';
}
// do your stuff
if($i == $numItems) {
echo "</div>";
}
}

Explode to array and print each element as list item

I have a set of numbers in a table field in database, the numbers are separated by comma ','.
I am trying to do the following:
Step 1. : SELECT set of numbers from database and explode it to array :
$array = explode(',', $set_of_numbers);
Step 2. : Print each element of the array as list item by using foreach loop :
foreach ($array as $list_item => $set_of_numbers){
echo "<li>";
print_r(array_list_items($set_of_numbers));
echo "</li>";}
Please anybody tell me what is wrong. Thank you.
$numbers = '1,2,3';
$array = explode(',', $numbers);
foreach ($array as $item) {
echo "<li>$item</li>";
}
Assuming your original $set_of_numbers is simply a CSV string, something like 1,2,3,4,..., then your foreach is "mostly" ok. But your variable naming is quite bonkers, and your print-r() call uncesary:
$array = explode(',', $set_of_numbers);
foreach($array as $key => $value) {
echo "<li>$key: $value</li>";
}
Assuming that 1,2,3,4... string, you'd get
<li>0: 1</li>
<li>1: 2</li>
<li>2: 3</li>
etc...
$numbers = "1,2,3";
$array = explode(",", $numbers);
/* count length of array */
$arrlength = count($array);
/* using for while */
$x = 0;
while ($x < $arrlength) {
echo "<li>$array[$x]</li>" . PHP_EOL;
$x++;
}
echo PHP_EOL;
/* using for classic */
for ($x = 0; $x < $arrlength; $x++) {
echo "<li>$array[$x]</li>" . PHP_EOL;
}
echo PHP_EOL;
/* using for each assoc */
foreach ($array as $value) {
echo "<li>$value</li>" . PHP_EOL;
}
echo PHP_EOL;
/* using for each assoc key */
foreach ($array as $key => $value) {
echo "<li>$key => $value</li>" . PHP_EOL;
}
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/ZqT4Yi" ></iframe>
You actually don't need to explode on the commas. You can just replace each comma with an ending tag followed by an opening tag and then wrap your whole string in an opening and closing tag.
$set_of_numbers = '1,2,3';
echo '<li>' . str_replace(',', '</li><li>', $set_of_numbers) . '</li>';
// outputs: <li>1</li><li>2</li><li>3</li>
No looping is necessary.
Here is answer for your question to get ride of your problem
$Num = '1,2,3,4,5,';
$Array = explode(',',$Num);
foreach ($Array as $Items)
{
echo "<li>&Items</li>"; // This line put put put in the list.
}
This can easily be achieved by the following code snippet:
<?php
$my_numbers = '1,12,3.2,853.3,4545,221';
echo '<ul>';
foreach(explode(',', $my_numbers) AS $my_number){
echo '<li>'.$my_number.'</li>';
}
echo '</ul>';
The above code will output the following HTML:
<ul><li>1</li><li>12</li><li>3.2</li><li>853.3</li><li>4545</li><li>221</li></ul>
Credits: http://dwellupper.io/post/49/understanding-php-explode-function-with-examples

JSON String add Link

I´ve got the a php that returns a JSON string:
$recipes = json_encode($arr);
That is my php-code how I output the recipe-title:
<?php
include('php/getAllRecipes.php');
$jsonstring = $recipes;
$recip = json_decode($recipes, true);
$i = 1;
var data = include('php/getAllRecipes.php')Data.Recipes;
foreach ($recip['Data']['Recipes'] as $key => $recipe) {
echo "$i.) &nbsp ";
echo $recipe['TITLE'];
$i = $i + 1;
echo "<br>";
}
?>
Now, I need to add a href to each title. The href should contain a link to recipe_search.php and I have to give it the id of each recipe.
How can I add this href?
<?php
include('php/getAllRecipes.php');
$jsonstring = $recipes;
$recip = json_decode($recipes, true);
?>
<ol>
<?php
foreach ($recip['Data']['Recipes'] as $key => $recipe) {
echo '<li>
<a href="/recipe_search.php?id=' . $recipe['ID'] . '">
' . $recipe['TITLE'] . '
</a>
</li>';
}
?>
</ol>
Use an ordered list (<ol>) instead of trying to create one yourself using a counter.
var data = include('php/getAllRecipes.php')Data.Recipes; is not valid PHP.
I assume that the id of the recipe is in $recipe['ID'].
Here you are...
foreach ($recip['Data']['Recipes'] as $key => $recipe)
{
// I guess $key is ID of your recipe...
echo sprintf('%d.) %s<br />', $i++, 'recipe_search.php?id=' . $key, $recipe['TITLE']);
}
Thats worked for me, just to test the above:
<?php
$i = 1;
foreach (array_fill(0, 40, 'recipe') as $key => $recipe)
{
// I guess $key is ID of your recipe...
echo sprintf('%d.) %s<br />', $i++, 'recipe_search.php?id=' . $key, $recipe);
}
?>

how to increment div id in php? [duplicate]

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.

Categories