How to find the last item of an array? - php

I have an array with three objects:
Ob1
Ob2
Ob3
I tried the following:
$args = array('child_of' => 184);
$categories = get_the_category($post->ID, $args);
$i = 0;
$len = count($categories);
foreach($categories as $cat) {
if ($i == 0) {
echo '<li><h2>'.$cat->name.', </h2></li>';
} else if ($i == $len - 2) {
echo '<li><h2>'.$cat->name.'</h2></li>';
}
$i++;
}
But I get
Ob1, Ob2
Basically if it is the last item I don't want the comma but I am not sure what is wrong with that code and why it is showing only two values.
If I do:
var_dump($len);
It gives me int(3)

You only want your $i conditional logic to apply to $len - 1.
The easiest way to do this is to simply swap the conditionals around and offset it by one:
foreach($categories as $cat) {
if ($i == $len - 1) {
echo '<li><h2>'.$cat->name.'</h2></li>';
} else {
echo '<li><h2>'.$cat->name.', </h2></li>';
}
$i++;
}

Related

Display even & odd numbers

I am trying loop through an array of random numbers if the the number is dividable by two then it's even and I then want to assign this to an array $even[], and if odd then assign it to the odd array. I have managed to display the results without using an array but for the sake of this I want to put them into their own array. However I can't seem to get this result I'm after all I get is this error: message Array to string conversion.
<?php
$numbers = array();
for ($i=0; $i<=1000; $i++) {
$numbers[]=mt_rand(1,1000);
if ($i % 2 == 0){
$even[]=$i;
} else {
$odd[]=$i;
}
}
echo $even;
echo $odd;
?>
Try this to echo the results.
foreach ($even as $evens){
echo $evens . '<br/>';
}
define $odd and $even as a array
$even = array();
$odd = array();
check if($i%2 == 0)
{
$even[] = $i;
}
else
{
$odd = $i;
}
var_dump($even);
var_dump($odd);

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

Add static number in the for loop index with PHP

I have following for loop code in PHP
for($i=10; $i<=50; $i=$i+10)
{
echo $i;
}
it will print
10 20 30 40 50
I want to add some specific $i value such as
$i=15 and $i=28
So it shold print
10 15 20 28 30 40 50
How should I edit the code ?
If you want specific values, you should make an array with those values and iterate through it:
$vals = array(10, 15, 20, 28, 30, 40, 50);
foreach ($vals as $i) {
echo $i;
}
if you have fixed place where to show these values .. then you can use simple if
for($i=10; $i<=50; $i=$i+10)
{
echo $i;
if($i == 10)
{
echo '15';
}
if($i == 20)
{
echo '28';
}
}
Ok, i'll play the "interview question" game :
for($i=10; $i<=50; $i++) {
if ($i % 10 === 0) {
echo $i;
}
else if ($i === 15 || $i === 28) {
echo $i;
}
}
Result at http://codepad.org/JBPkm8W1
You can improve this answer by adding an "allowed values" table :
$allowed = array (15, 28); // List here all the non % 10 value you want to print
for($i=10; $i<=50; $i++) {
if ($i % 10 === 0) {
echo $i;
}
else if (in_array($i, $allowed)) {
echo $i;
}
}
The result at http://codepad.org/w8Erv17K
The easiest way is to use a foreach loop like #WaleedKhan wrote.
To prepare the array you can use for loop like you did:
$vals = array();
for($i = 10; $i <= 50; $i = $i + 10){
$vals[] = $i;
}
$vals[] = 15;
$vals[] = 28;
sort($vals);
foreach(...
Try this :
$extra = array(15,28);
$res = array();
for($i=10; $i<=50; $i=$i+10){
$res[] = $i;
}
$result = array_merge($res,$extra);
sort($result);
echo "<pre>";
print_r($result);
You can put the 15 and 28 values in array and get the values using array_intersect.
Create an array to hold the 15 and 28 values (intermeditate values).
$new_vals = array(15,28);
Now in your for loop you can call array_insersect function to get the intermediate values. Your final code will look like this.
$new_vals = array(15,28);
for($i=10; $i<=50; $i=$i+10)
{
echo $i;
$val_range = range($i,$i+10);
$new_array = array_intersect($new_vals , $val_range);
foreach($new_array as $value)
{
echo $value;
}
}
You could do something like this:
function EchoLoopStuff($start, $to, $step) {
for($i=$start; $i<=$to; $i=$i+$step) {
echo $i;
}
}
But you'd need to add some checking to save yourself from issues when inputs contradict.

Continue foreach loop from middle

I have this for each loop:
foreach($downloads as $dl) {
echo seosvelniau2($dl['title']);
}
By default it gives me 50 results, is there any way to split this foreach loop into two (1-25) and (26-50), so I can put both into two separate table columns?
I know, that i can make loop to show only first 25 results like this:
$i=0;
foreach($downloads as $dl) {
$i++;
echo seosvelniau2($dl['title']);
if ($i == 25)
break;
}
but how to do second loop to show (26-50) results?
You can divide the array $downloads even before the loop.(using array_chunk)
$Chunks = array_chunk($downloads , 25);
foreach($Chunks[0] as $dl)
{
//Group 1
}
foreach($Chunks[1] as $dl)
{
///Group2
}
EDIT: Here's a general example: (In case you have more than 50 elements)
$Chunks = array_chunk($downloads , 25);
foreach($Chunks as $oneChunk)
{
//New group of 25 elements.
foreach($oneChunk as $dl)
{
}
}
Two different approaches:
Use each to iterate over the array.
$i = 0;
while(list($id, $item) = each($array)) {
echo $item;
if (++$i == 25) { break; }
}
while(list($id, $item) = each($array)) {
echo $item;
}
If you don't need that array after the loop is complete, you can simply shift the items:
$i = 0;
while (++$i < 25 && count($array)) {
$item = array_shift($array);
echo $item;
}
foreach ($array as $item) {
echo $item;
}
You could switch the columns in between:
$i = 0;
foreach ($downloads as $dl) {
if (++$i === 25) echo '</tr><tr>';
echo seosvelniau2($dl['title']);
}
Another option:
$i=0;
foreach($downloads as $dl) {
$i++;
if ($i <= 25){
//first 25
}else{
//rest
}
}
If you're in the process if drawing an HTML table, and you need to switch td, just do something like this:
for ( $i = 0; $i < count( $downloads ); $i++ )
{
echo seosvelniau2( $downloads[ i ][ 'title' ] );
if ( $i % 25 == 0 )
{
echo( '</td><td>' );
}
}
This will create a new columns every 25 values.
Wouldn't you just use a normal for loop instead of foreach? Then you can determine the start and end points manually, like so.
Then you should have something more or less like this:
for ($i=1; $i<=25; $i++)
{
echo "The number is " . $i . "<br />";
}
for ($i=26; $i<=50; $i++)
{
echo "The number is " . $i . "<br />";
}

PHP explode - running loop through each array item

Here's the issue:
I retrieve the following data string from my database:
$row->exceptions = '1,2,3';
After explode I need the below code to check each one of the exploded pieces
$exceptions = explode(",", $row->exceptions);
//result is
//[0] => 1
//[1] => 2
//[2] => 3
for ($i = 0; $i <= $row->frequency; $i++) {
if ($exceptions[] == $i) {
continue;
} else {
//do something else
}
}
How can I make $exceptions[] loop through all keys from the exploded array so it evaluates if ==$i?
Thanks for helping.
It should suffice to substitute:
if($exceptions[] == $i)
with:
if(in_array($i,$exceptions))
By the way, it eliminates the need for a nested loop.
Ah, should be straightforward, no?
$exceptions = explode(",", $row->exceptions);
for ($i = 0; $i <= $row->frequency; $i++) {
foreach($exceptions as $j){
if($j == $i){
// do something
break;
}
}
}
I think I understand what you are asking. Here's how you would test within that loop whether the key equals $i.
for ($i = 0; $i <= $row->frequency; $i++)
{
foreach ($exceptions as $key => $value)
{
if ($key == $i)
{
continue;
}
}
}

Categories