Trying to Reverse Order of Images in PHP - php

I'm trying to reverse the order of images that are displayed. I'm a PHP noob and I'm not sure how to do it. I guess I need to reverse the order of foreach that is displayed, but I'm not entirely sure how to do that.
<div class="yacht-view-right">
<?php
if (count($tpl['gallery_arr']) > 0)
{
$is_open = false;
foreach ($tpl['gallery_arr'] as $k => $v)
{
if ($k == 0)
{
$size = getimagesize(BASE_PATH . $v['medium_path']);
?>
<p><?php print_r(array_keys($v));
print_r(array_VALUES($v));
echo (count($tpl['gallery_arr']))
?></p>
<div class="yacht-view-pic" id="yacht-view-pic" style="width:<?php echo $size[0]; ?>px; height: <?php echo $size[1]; ?>px;">
<img id="yacht-view-medium-pic" src="<?php echo BASE_PATH . $v['medium_path']; ?>" alt="<?php echo htmlspecialchars(stripslashes($v['title'])); ?>"/> </a>
</div>
<?php
}h
$is_open = true;
?>
<div class="yacht-view-img">
<a href="<?php echo BASE_PATH . $v['large_path']; ?>" data-lightbox="yachts">
<img src="<?php echo BASE_PATH . $v['small_path']; ?>" alt="<?php echo htmlspecialchars(stripslashes($v['title'])); ?>" />
</a>
</div>
<?php
/*if ($k > 0 && ($k + 1) % 4 === 0)
{
$is_open = false;
?><div class="clear_left"></div><?php
}*/
}
if ($is_open)
{
?>
<div class="clear_left"></div>
<?php
}
} else {
}
?>

You can simply use array_reverse() before starting your foreach iteration:
$is_open = false;
$tpl['gallery_arr'] = array_reverse( $tpl['gallery_arr'], true );
foreach ($tpl['gallery_arr'] as $k => $v)

You could simply reverse the order of the array using array_reverse before iterating through it with foreach:
foreach ( array_reverse( $tpl['gallery_arr'] ) as $k => $v)
or you could iterate in reverse using a counter (which may have slightly better performance, if the array is large):
$gallery = $tpl['gallery_arr'];
for($i = $first = count($gallery) - 1; $i >= 0; $i-- ) {
$v = $gallery[$i];
if ( $k == $first ) {
...
}

So it looks like you could use the array_reverse() function
$tpl['gallery_arr'] = array_reverse( $tpl['gallery_arr'], true );
foreach ($tpl['gallery_arr'] as $k => $v){
...
}
Or use a regular for loop with inverted parameters.
for($k = count($tpl['gallery_arr']) - 1; $k >= 0; $k--){
$v = $tpl['gallery_arr'][$k];
...
}

Related

PHP - How to wrap every 2 items of a 'for' loop within a div

I'm looking for a way to wrap every too items of this very basic for loop within a div :
<?php
for( $i=1; $i<=50; $i++ )
{
echo "<div><a href='item-".$i."'>".$i."</a></div>";
}
?>
This produces the following :
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
The output i need would be :
<div>1 2</div>
<div>3 4</div>
Thanks
Easiest way i can think of is by doing this. This also works if you have a resultset from a database, or an array of item objects, just replace the range() function with the array.
<?php
foreach (array_chunk(range(1, 50), 2) as $chunk) {
echo "<div>";
foreach ($chunk as $itemId) {
echo "<a href='item-" . $itemId . "'>" . $itemId . "</a>";
}
echo "</div>" . PHP_EOL;
}
Use modulo operator
code:
<?php
$chunks = 2;
$display = true;
for( $i=1; $i<=6; $i++ )
{
if ($display && ($i % $chunks || $chunks === 1)) {
echo "<div>";
$display = false;
$last = true;
}
echo "<a href='item-".$i."'>".$i."</a>";
if (!($i % $chunks)) {
echo "</div>" . PHP_EOL;
$display = true;
$last = false;
}
}
if ($last) {
echo "</div>" . PHP_EOL;
}
generates:
<div><a href='item-1'>1</a><a href='item-2'>2</a></div>
<div><a href='item-3'>3</a><a href='item-4'>4</a></div>
<div><a href='item-5'>5</a><a href='item-6'>6</a></div>
and with:
$chunks = 3;
you will get:
<div><a href='item-1'>1</a><div><a href='item-2'>2</a><a href='item-3'>3</a></div>
<div><a href='item-4'>4</a><div><a href='item-5'>5</a><a href='item-6'>6</a></div>
and so one.

I want to echo something only on the first time foreach runs

I want to echo something only on the first time foreach() runs!
let's say if I have an array $i
$i = array(............);
and I want to use it in foreach like...
foreach($i as $key => $value) {
echo '<h1>'.$key.'</h1>';
echo '<p>'.$value.'</p>';
}
while this foreach runs the first time only i want to add class="show" to the h1 tag.
How to do that?
Update code:
$i=['hello','world'];
foreach($i as $key => $value) {
$class= ($key == 0)?'show':'';
echo '<h1 class="'.$class.'">'.$key.'</h1>';
echo '<p>'.$value.'</p>';
}
Output:
<div>
<h1 class="show">0</h1><p>hello</p>
<h1 class="">1</h1><p>world</p>
</div>
You'll need to add a var to track that
$first = 0;
foreach($i as $key => $value) {
$show=($first == 0) ? 'h1 class=show' : 'h1';
echo '<$show>'.$key.'</h1>';
echo '<p>'.$value.'</p>';
$first++;
}
There are many ways to do it, but this might be easier to read
if you have single dimension array then you can use
$i=['test1','test2','test3'];
foreach($i as $key => $value) {
if($key == 0){
echo $key;
echo '<br>';
echo '<p>'.$value.'</p>';
}
}
if you have an associative array
$i=array('a'=>'test1','b'=>'test2','c'=>'test3');
$j = 0;
foreach($i as $key => $value) {
if($j == 0){
echo $key;
echo '<br>';
echo '<p>'.$value.'</p>';
}
$j++;
}
output will be

Split array into div [duplicate]

This question already has answers here:
Break PHP array into 3 columns
(7 answers)
Closed 7 years ago.
I have this array :
$result = array('description1', 'description2', 'description3', 'description4', 'description5'
I want to split this array into divs like this :
$result[0] - $result[1] => put these into a div
$result[2] - $result[3] => put these into a div
$result[4] => put this into a div
My entire structure
$content = get_the_content();
$description = array();
$j=0;
if (preg_match_all('/<div id="description" class="description">([^<]*)<\/div>/', $content, $match)) {
for( $i = 0; $i < count($match[0]); $i = $i+1 ) {
$description[] = $match[0][$i];
}
}
$attachments =& get_children($args);
$arrayMatches = array();
if ($attachments) {
foreach(array_chunk($attachments, 2) as $img) {
echo '<div class="two_cols">';
foreach($img as $attachment) {
foreach($attachment as $attachment_key => $attachment_value) {
$imageID = $attachment->ID;
$imageTitle = $attachment->post_title;
$imagearray = wp_get_attachment_image_src($attachment_value, $size, false);
$imageAlt = get_post_meta($imageID, '_wp_attachment_image_alt', true);
$imageURI = $imagearray[0]; // 0 is the URI
$imageWidth = $imagearray[1]; // 1 is the width
$imageHeight = $imagearray[2]; // 2 is the height
?>
<div class="col_1_2">
<!-- A picure Here -->
<?php $arrayMatches[] = $match[0][$j]; ?>
</div>
<?php
break;
}
$j++;
}
$arrayMatches = array_chunk($arrayMatches, 2);
echo "<div>";
foreach($arrayMatches as $v) {
echo implode($v);
}
echo "</div>";
echo '</div>';
}
}
This should work for you:
Just chunk your array with array_chunk(). And then you can simply loop through your array, output it into a div and implode() the elements.
<?php
$result = array('description1', 'description2', 'description3', 'description4', 'description5');
$result = array_chunk($result, 2);
foreach($result as $v) {
echo "<div>" . implode(" ", $v) . "</div>";
}
?>
output:
<div>description1 description2</div>
<div>description3 description4</div>
<div>description5</div>
EDIT:
As from your updated array structure just grab all values first like this:
$result = [];
$arr = array(['description1'], ['description2'], 'description3', 'description4', 'description5'); //example
array_walk_recursive($arr, function($v, $k)use(&$result){
$result[] = $v;
});
$result = array_chunk($result, 2);
Can you not just echo them in divs:
<div>
<?php echo $result[0] . "-" . $result[1]; ?>
</div>
<div>
<?php echo $result[2] . "-" . $result[3]; ?>
</div>
<div>
<?php echo $result[4]; ?>
</div>
You just need to control whether you are in the last 2 positions or not.
echo '<div>';
for ($i=0;$i<count($result);$i=$i+2) {
if ($i+1 >= count($result)) {
echo $result[$i];
} else {
echo $result[$i].$result[$i+1];
echo '</div><div>';
}
}
echo '</div>;

Proper PHP syntax for cycleing through an array with the index

I am newish to PHP and I am trying to cycle through an array and stop after 5 items.
I am using the following:
$images = ( $f->APIVer == "1.2.2" ) ? $images['Images'] : $images;
// Display the thumbnails and link to the medium image for each image
foreach ( $images as $index => $image) {
echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
}
while ( $index < 5 );
}
Although it does not seem to work...
Am I doing something wrong?
Thanks in advance
If the array has a zero based index you can do:
foreach ( $images as $index => $image) {
if ($index == 5) break;
echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
}
Otherwise you can add your own counter:
$i = 0;
foreach ( $images as $index => $image) {
$i++;
if ($i == 5) break;
echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
}
What you tried is another type of loop:
$index = 0;
do {
echo '<li><a href="'.$images[$index]['XLargeURL'].'"><img src="'.$images[$index]['TinyURL'].'" alt="thumbnail"/></li>';
$index++;
} while ( $index < 5 );
Or:
$index = 0;
while ( $index < 5 ) {
echo '<li><a href="'.$images[$index]['XLargeURL'].'"><img src="'.$images[$index]['TinyURL'].'" alt="thumbnail"/></li>';
$index++;
}
Another alternative would be a for loop:
for($index=0; $index < 5; $index++) {
echo '<li><a href="'.$images[$index]['XLargeURL'].'"><img src="'.$images[$index]['TinyURL'].'" alt="thumbnail"/></li>';
}
$images = ( $f->APIVer == "1.2.2" ) ? $images['Images'] : $images;
$nm = 0;
foreach ( $images as $index => $image) {
if($nm < 5){
echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
}
$nm++;
}
It should be like this:
$images = ( $f->APIVer == "1.2.2" ) ? $images['Images'] : $images;
$i = 0;
// Display the thumbnails and link to the medium image for each image
foreach ( $images as $index => $image) {
if ($i == 5) break;
echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
$i++;
}
while is a loop on its own, just like foreach.
Given that $index is an integer you could just break out of the loop:
foreach ($images as $index => $image) {
echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>';
if ($index >= 5) {
break;
}
}

Loop within Loop causing undesired output

I have the following loop...
for ($i = 1; $i <= 10; $i++) {
echo '<span class="srch-val-'.$i.'">'.apply_filters(" $value\n", $value)."</span>";
}
within...
while ( $query->have_posts() ) : $query->the_post();
if ( $keys = get_post_custom_keys() ) {
echo "<div class='clearfix card-prod ".($i==0?'first':'')."'><span class='card-title'>";
echo the_title();
echo "</span>";
foreach ( (array) $keys as $key ) {
$keyt = trim($key);
if ( '_' == $keyt{0} || 'pricing' == $keyt || 'vehicleType' == $keyt || 'coverageRegion' == $keyt || 'locationType' == $keyt )
continue;
$values = array_map('trim', get_post_custom_values($key));
$value = implode($values,', ');
for ($i = 1; $i <= 10; $i++) {
echo '<span class="srch-val-'.$i.'">'.apply_filters(" $value\n", $value)."</span>";
}
}
echo "\n"; echo '<img src="wp-content/themes/cafc/images/top-choice.jpg" alt="Top Choice" class="topchoice">';echo '<img src="wp-content/themes/cafc/images/cards/dummy.png" />'; echo the_excerpt()."</div>";}
$i++;
endwhile;
When I execute my code however, say my while() loop returns 4 values, my for() loop then outputs 10 of the same thing, in my browser its shown as...
All I want to do is for each <span class="srch-val'> is to add a number after each 'srch-val' class, so srch-val-1, srch-val-2 etc...
You have an extra for-loop inside your foreach-loop. Remove this loop and just do the echo directly inside the foreach-loop and increment $i each time you actually use it.
Like this:
$i = 1;
while ( $query->have_posts() )
{
$query->the_post();
if ( $keys = get_post_custom_keys() )
{
echo "<div class='clearfix card-prod ".($i==0?'first':'')."'><span class='card-title'>";
echo the_title();
echo "</span>";
foreach ( (array) $keys as $key )
{
$keyt = trim($key);
if ( '_' == $keyt{0} || 'pricing' == $keyt || 'vehicleType' == $keyt || 'coverageRegion' == $keyt || 'locationType' == $keyt )
continue;
$values = array_map('trim', get_post_custom_values($key));
$value = implode($values,', ');
echo '<span class="srch-val-'.$i.'">'.apply_filters(" $value\n", $value)."</span>";
$i++; // move the incrementer here so that you only increment when you actually use it.
}
echo "\n"; echo '<img src="wp-content/themes/cafc/images/top-choice.jpg" alt="Top Choice" class="topchoice">';echo '<img src="wp-content/themes/cafc/images/cards/dummy.png" />'; echo the_excerpt()."</div>";
}
}
You create a variable at the beginning of your foreach-loop (say $counter == 1;)
Than your For-loop should be:
for($i = $counter; $i <= $counter+10; $i++){
//do your span-class thing here
}
And at the end of the foreach loop do: $counter += 10;

Categories