I have a simple foreach loop that outputs the information I want.
However, I want to wrap it with a div for every two results.
I tried the modulus operator with no success (the result applied for every result).
So, my code:
foreach ($result->data as $info) {
// A open div to wrap two results
echo 'something';
// An closing div to wrap the previous two results
}
This will do it!
foreach ($result->data as $i=>$info) {
if ($i % 2 == 0) echo '<div>';
echo $info;
if ($i % 2 == 1) echo '</div>';
}
if (count($result->data) % 2 == 1) echo '</div>';
exactly what you asked ;)
Most simple way: Iterate in steps of 2.
for ($cc = 0; $cc<count($result->data); $cc += 2) {
// here >> start div container for both
echo $result->data[$cc];
if (defined($result->data[$cc+1]))
echo $result->data[$cc+1];
// here >> end div container for both
}
HTML omitted for clearness.
You can also add an else branch to output a placeholder if the result contains an odd number of items.
add an index count then check that its divisible by two in the code.
IN THIS CASE the if block needs to be at the top of the foreach loop, since I started $i at 0. Please stop editing that portion :)
$i = 0;
// Create first new div before loop, here.
echo '<div>'; //first div
foreach ($result->data as $info) {
// An closing div to wrap the previous two results
if ($i % 2){
// Code here would occur after each two iterations
// IE: close div then open new one. something like this
echo '</div><div>';
}
// A open div to wrap two results
echo 'something';
$i++;
}
// close final div after loop, here.
echo '</div>';
For outputting every two results from array you can also use
<?php
$array = range( 1, 20 );
foreach( array_chunk( $array, 2 ) as $pair ) {
echo '<div>' , implode( ' ', $pair ) , '</div>';
}
// <div>1 2</div>
// <div>3 4</div>
// etc
?>
set 2 variables, string and int
save the value in string variable if the value of the int variable is not even
when the second variable is an even number
wrap in div
//just simply
<?php
foreach($result->data as $i=>$info){
if($i<5){
echo $info
}
}
?>
Related
I asked a similar question earlier but I couldn't get a clear answer to my issue. I have a function "isParent" that gets 2 pieces of data. Each 1 of the 2 gets a string separating each value with a , or it just gets a plain int and then checks if the first value given is a parent of the second.
I pull the 2 bits of data in and explode them but when I go through my nested for loop and try to test
$toss = $arr1[$i];
print_r($toss);
It comes up blank. I have no idea what the issue is: Here is the full code of the function...
function isParent($parent, $child)
{
$parentArr = explode(',', $parent);
$childArr = explode(',',$child);
//Explode by Comma here. If array length of EITHER parentArr or childArr > 1 Then throw to an Else
if(count($parentArr) <= 1 && count($childArr) <= 1) //If explode of either is > 1 then ELSE
{
$loop = get_highest_slot(15);
for($i = $loop; $i > 0; $i--)
{
$temp = get_membership_from_slot($i,'id_parent','id_child');
if($temp['id_parent'] == $parent && $temp['id_child'] == $child)
{
return 1;
}
}
}
else //set up a for loop in here so that you traverse each parentArr value and for each iteration check all child values
{
$i = count($parentArr);
$c = count($childArr);
for(;$i >=0;$i--) //Loop through every parent
{
for(;$c >=0;$c--)
{
echo '<br>$i = ';
print_r($i);
echo '<br><br>Parent Arr at $i:';
$toss = $parentArr[$i];
echo $toss;
echo '<br>';
print_r($childArr);
echo '<br><br>';
if(isParent($parentArr[$i],$childArr[$c])) //THIS CAUSES AN INFINITE YES! Learn how to pull an array from slot
{
return 1;
}
}
}
}
return 0;
}
You are missing some code for the slot procedures. Apart from that, you probably need to use a different variable for the inner for loop. because $c will be 0 after the first iteration of $i.
Thanks for the help! The issue was in the recursive call back to the top of the function. It was tossed empty slots and when comparing 2 empty slots it returned a false positive. A quick !empty() check fixed it.
I want to echo these links as following:
Title
http://www.link.com
Title 2
http://www.link2.com
Instead they come like this:
Title
http://www.link.com
http://www.link2.com
Title2
http://www.link.com
http://www.link2.com
Here is the code that I am using:
foreach($links as $link ){
echo $link."<br>";
foreach($linksx as $linkx ){
echo $linkx."<br>";
}
}
Thank you for your help.
As you have 2 differents arrays, you have to iterate over them on the same time, not one inside the other.
Assuming arrays are indexed numerically (basic array), and have the same size (the same number of elements), you can write
for($i = 0 ; $i < count($links) ; $i++)
{
echo $links[$i] . "<br />";
echo $linksx[$i];
}
It's because you are looping over the entire $linksx array for each element in $links. What you want is to loop over one array then get its counterpart in the other array.
foreach($links as $key=>$link){
$linkx = $linksx[$key];
echo $link."<br>".$linkx."<br>";
}
Did you mean to nest the loops?
foreach($links as $link )
{
echo $link."<br>";
}
foreach($linksx as $linkx )
{
echo $linkx."<br>";
}
After applying what wrapping objects using math operator, I just tought it will be over. But no. By far.
<?php
$faces= array(
1 => '<div class="block">happy</div>',
2 => '<div class="block">sad</div>',
(sic)
21 => '<div class="block">angry</div>'
);
$i = 1;
foreach ($faces as $face) {
echo $face;
if ($i == 3) echo '<div class="block">This is and ad</div>';
if ($i % 3 == 0) {
echo "<br />"; // or some other wrapping thing
}
$i++;
}
?>
In the code I have to put and ad after the second one, becoming by that the third object. And then wrap the three all in a <div class="row"> (a br after won't work out by design reasons). I thought I will going back to applying a switch, but if somebody put more elements in the array that the switch can properly wrap, the last two remaining elements are wrapped openly.
Can i add the "ad" to the array in the third position? That would make things simplier, only leaving me with guessing how to wrap the first and the third, the fourth and the sixth, an so on.
First, insert the ad:
array_splice($faces, 2, 0, array('<div class="block">this is an ad</div>'));
Then, apply the wrapping:
foreach (array_chunk($faces, 3) as $chunk) {
foreach ($chunk as $face) {
echo $face;
}
echo '<br />';
}
You could just split the array in two, insert your ad and then append the rest:
// Figure out what your ad looks like:
$yourAd = '<div class="block">This is and ad</div>';
// Get the first two:
$before = array_slice($faces, 0, 2);
// Get everything else:
$after = array_slice($faces, 2);
// Combine them with the ad. Note that we're casting the ad string to an array.
$withAds = array_merge($before, (array)$yourAd, $after);
I think nickb's note about using the comparison operator rather than assignment will help get your wrapping figured out.
I have the following structure :
<?php
$i = 0;
foreach ($users as $user) {
$i++;
$string = '<span>The number is $i</span>';
$string = preg_replace('/\<span.*?\/>$/e','',$string);
echo $string;
}
?>
It appends the $string the number of times foreach loop iterate whereas i just want it to display one time as The number is 4 at the end of the loop. preg_replace works if outside of the loop. How can i echo the output one time and delete rest. I need to do it within the loop and not outside it.
This will do it:
$i = 0;
foreach ($users as $user) {
$i++;
if ($i == count($users)) {
$string = '<span>The number is $i</span>';
$string = preg_replace('/\<span.*?\/>$/e','',$string);
echo $string;
}
}
Though, you might want to consider other options for achieving this. You may maintain your $i variable and output it right after the loop, as this is what this does exactly.
Or, you could just echo "<span>The number is ".count($users)."</span>";.
In my answer, I assumed you totally can't change this things, and that your problem is more complicated than this simple preg_replace. If it's not, consider simplifying things.
The solution I think you need here is output buffering:
// Start the output buffer to catch the output from the loop
ob_start();
$i = 0;
foreach ($users as $user) {
$i++;
// Do stuff
}
// Stop the output buffer and get the loop output as a string
$loopOutput = ob_get_clean();
// Output everything in the correct order
echo '<span>The number is '.$i.'</span>'.$loopOutput;
Witch is the best way to print a letter (beginning from A) before each row of a list without using html ordered list <ol><li></li>...</ol> and without using an array that contain the alphabet?
es:
A. first row
B. second row
C. third row
thanks for your suggestion!
How about this, using ++ on a variable containing a letter...
$letter = 'A';
foreach ($list as $item) {
echo $letter++, '. ', $item, "\n";
}
See the increment operator's manual page for more information on this behaviour. Essentially, calling ++ on a one-character string, where that character is an A-Za-z letter, will make the string into the next letter.
You could use a string and substr it on every iteration:
<?php
$alph = 'abcdefghijklmnopqrstuvwxyz';
$rows = array(); //whatever your rows are that you're printing
$i = 0;
foreach($rows AS $r): ?>
<?php echo substr($alph, $i, 1); ?> x row<br>
<?php $i ++; endforeach; ?>
Something like this?
<?php
for($i=0; $i<10; $i++)
{
echo chr(65+$i) . '. ' . $1;
}
?>
$l = 'a';
foreach($rows as $row) {
echo strtoupper($l).". {$row}\n";
$l++
}
Depending upon how long your list is, you can get away with this:
$start = 'A';
foreach ($lists as $li) {
echo "$start. $li\n";
$start++;
}
If you don't even want to specify the start, you can use the ascii codes too.
foreach ($lists as $num => $li) {
echo chr($num + 65) . ". $li\n";
}