Proper PHP syntax for cycleing through an array with the index - php

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

Related

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

Trying to Reverse Order of Images in 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];
...
}

Limit number of sub_menu items to 4

I am trying to limit the number of sub_menu items (li) to maximum of 4. I'm no php developer but gave it a go with some code as provided below.
This is the existing code, which will just keep displaying it all, no limit set right now.
if (count($sub_menu_array)) {
echo '<nav id="sub-nav"><ul>';
foreach ($sub_menu_array as $sub_menu_row) {
// print_r($sub_menu_row);
echo '<li>'.strtoupper($sub_menu_row['categoryName']).'</li>';
}
echo '</ul></nav>';
} else {
echo '<nav id="sub-nav"><ul><li></li></ul></nav>';
}
Here is what I tried but it ended up displaying nothing instead.
if (count($sub_menu_array)) {
echo '<nav id="sub-nav"><ul>';
$i = 0;
foreach ($sub_menu_array as $sub_menu_row => $v) {
// print_r($sub_menu_row);
echo '<li>'.strtoupper($sub_menu_row['categoryName']).'</li>';
if (++$i == 3) break;
}
echo '</ul></nav>';
} else {
echo '<nav id="sub-nav"><ul><li></li></ul></nav>';
}
Syntax of PHP foreach statement has two different variants
foreach (array_expression as $value){
statement
}
foreach (array_expression as $key => $value)
statement
When you chanched code from
foreach ($sub_menu_array as $sub_menu_row) {
to
foreach ($sub_menu_array as $sub_menu_row => $v) {
You also changed values what appropriated to $sub_menu_row. For example:
$sub_menu_array = array ('a','b');
In the first variant at first iteration
$sub_menu_row=='a'
and in second variant
$sub_menu_row==0 #array's element key
$v=='a' #value
There are two solutions
Simply remove '=> $v'
Change $sub_menu_row to $v inside foreach statement
You have changed foreach, you should now use $v as a value.
if (count($sub_menu_array)) {
echo '<nav id="sub-nav"><ul>';
$i = 0;
foreach ($sub_menu_array as $sub_menu_row => $v) {
// print_r($sub_menu_row);
echo '<li>'.strtoupper($v['categoryName']).'</li>';
if (++$i == 3) break;
}
echo '</ul></nav>';
} else {
echo '<nav id="sub-nav"><ul><li></li></ul></nav>';
}
This should be enough for the menu part:
echo '<nav id="sub-nav"><ul>';
$i = 0;
foreach ($sub_menu_array as $sub_menu_row => $v) {
if($i < 4) {
echo '<li>'.strtoupper($sub_menu_row['categoryName']).'</li>';
}
$i++;
}
echo '</ul></nav>';
Insert this line before displaying the menu
$sliced_sub_menu_array = array_slice($sub_menu_array, 0, 4);
and then
foreach ($sliced_sub_menu_array as $sub_menu_row => $v) {
// displaying here
}
Use this code .
<?php
if (count($sub_menu_array)) {
echo '<nav id="sub-nav"><ul>';
$i = 0;
foreach ($sub_menu_array as $sub_menu_row => $v) {
// print_r($sub_menu_row);
echo '<li>'.strtoupper($sub_menu_row['categoryName']).'</li>';
if ($i == 3)
{
break;
}
$i++;
}
echo '</ul></nav>';
} else {
echo '<nav id="sub-nav"><ul><li></li></ul></nav>';
}
?>

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;

Adding a css class in a foreach string

I have the following code which displays related items in a wordpress template but I would like to add a class that every second item is attached with a css class of right, what do I need to modify to achieve this?
<?php $rel = $related->show(get_the_ID(), true);
foreach ($rel as $r) :
echo '<div class=related-item><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
endforeach;?>
Although this is Wordpress related I thought it was more related to general PHP coding so psoting here rather than at WPSE.
try this
<?php $rel = $related->show(get_the_ID(), true);
$count = 0;
foreach ($rel as $r) {
$class= ($count%2 == 0)?"right":"";
echo '<div class="related-item '.$class.'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
$count++;
}?>
If the array has a sequenced index you can use either a modulo calculation or a bitwise operation. If the array is based of non-numeric or not sequenced numbers you need to add a counter.
$i & 1 // odd using bitwise
$i % 2 // odd modulo
So what you would get is the following:
$i = 0;
foreach ($rel as $r) { // note that I have used curly brackets. I think it is cleaner more standard
$i++;
$classes = array('related-item');
if ($i % 2 == 0) $classes[] = 'right';
echo '<div class="'.implode(' ', $classes).'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
Or using bitwise:
$i = 0;
foreach ($rel as $r) { // note that I have used curly brackets. I think it is cleaner more standard
$i++;
$classes = array('related-item');
if ($i & 2 == 0) $classes[] = 'right';
echo '<div class="'.implode(' ', $classes).'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
Or if $rel has a zero based sequenced index:
foreach ($rel as $index => $r) { // note that I have used curly brackets. I think it is cleaner more standard
$classes = array('related-item');
if ($index & 2 == 1) $classes[] = 'right';
echo '<div class="'.implode(' ', $classes).'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
<?php $rel = $related->show(get_the_ID(), true);
$i = 0;
foreach ($rel as $r) {
echo '<div class=related-item' . ($i++ % 2 ? '' : ' right') . '><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
?>
Something like this. My advice is to try to use curly braces instead of foreach () : endforeach;
Do you mean:
$i = 0;
foreach ($rel as $r) :
$class = (($i % 2) == 0) ? "your_class" : "";
echo '<div class="related-item $class"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.''.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
$i++;
endforeach;
<?php
foreach($rel as $key => $r) {
/* here we check if $key is even and assign class name or empty string to $class variable */
($key%2) ? $class = 'your-class-name' : $class = '';
/* and here we just add $class variable to 'class="related-items " part. */
/* so if $key is odd then $class will be empt and your div will have only 'related-item' class, and if $key is even then $class will hold 'your-class-name' value and div will have two classes: related-item and your-class-name */
echo '<div class="related-item '.$class.'"><a href='.get_permalink($r->ID).'>'.'<div class=page-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
}
?>

Categories