how to increment div id in php? [duplicate] - 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
}
?>

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);
}
?>

What is the quickest way to randomize a data set?

For a multiple choice quiz application i would like to show the dummy answers with the correct answer. But with the correct answer being in a different position at each different question.
This is what i've tried but it doesn't seem to be working:
if ($question->type == 1)
{
echo "<div id='dummy_answers'>";
//Show Dummy
echo '<h3>Dummy Answers</h3>';
//Get Dummy Answers
$query = $this->test_model->getDummyAnswers($question->id);
$dummy_num = 1;
foreach ($query->result() as $row)
{
$rand_number = rand(1, 3);
if ($dummy_num == $rand_number)
{
$dummy_num = $rand_number + 2;
echo '<h4>Answer '.$dummy_num.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
//Now echo the real answer
echo '<h4>Answer '.$rand_number.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>'; //Get id's for each.echo $row->id;
}
else
{
echo '<h4>Answer '.$dummy_num.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
$dummy_num++;
}
}
echo '</div>';
echo ' <hr/>';
}
?>
You should use shuffle function.
In your case it will be:
if ($question->type == 1)
{
echo "<div id='dummy_answers'>";
//Show Dummy
echo '<h3>Dummy Answers</h3>';
//Get Dummy Answers
$query = $this->test_model->getDummyAnswers($question->id);
$answers=$query->result();
shuffle($answers);
foreach ($answers as $nr=>$row)
{
echo '<h4>Answer '.($nr+1).'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
}
echo '</div>';
echo ' <hr/>';
}
?>
Put the answers in an array the use shuffle
$random_array = shuffle($answers);
All you need to do is put the keys for your answers in an array and call shuffle(). Something like this:
$keys = array_keys($answers);
shuffle($keys);
for ($key in $keys) {
echo $answers[$key];
}
I would suggest putting all the answers into an array and using the shuffle() function to randomize them. Once they're shuffled, just iterate the array with a loop and build the markup.
You could put the results into an array (1 correct and 3 incorrect), then shuffle, then output them?
$answers = array();
array_push($answers, "answer1");
array_push($answers, "answer2");
array_push($answers, "answer3");
array_push($answers, "answer4");
shuffle($answers);
foreach ($answers as $answer) {
echo $answer;
}

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.

Categories