Find the Last Element of an Array While Using a Foreach Loop in PHP

Find the last element of an array while using a foreach loop in PHP

It sounds like you want something like this:

$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
if(++$i === $numItems) {
echo "last index!";
}
}

That being said, you don't -have- to iterate over an "array" using foreach in php.

How can I detect the first and the last element inside a foreach loop?

No need of foreach loop, just use a foreach loop and count. the foreach loop return an array.

$path = "monkey/cat/horse";

$arr = explode("/", $path);
$count = count($arr);


foreach($arr as $key => $value){
if($key == 0) echo "first:".$value;
elseif($key == ($count - 1)) echo "last:".$value;
}

Result

first:monkey
last:horse

Foreach with reference causing array's last element to repeat

In your first example, the $item variable still holds a reference to the last value of the $arr when the loop is done.

foreach ($arr as &$item) {
$item[] = $item[0];
}

If you use print_r(get_defined_vars()); you can see that there is a key in the array with name item

The behaviour of the double value at the end of the foreach is described here and It is recommended to destroy the specified variables using unset($item)

You can also use a different variable name.


Using array_map, the callback gets a function argument passed by name, which is bound to the function scope.

If you run print_r(get_defined_vars()); after using array_map you can see that there is no key named item

PHP How to determine the first and last iteration in a foreach loop?

You could use a counter:

$i = 0;
$len = count($array);
foreach ($array as $item) {
if ($i == 0) {
// first
} else if ($i == $len - 1) {
// last
}
// …
$i++;
}

why the last element of array changed after 2 foreach loop?

From the foreach manual:

Warning Reference of a $value and the last array element remain even
after the foreach loop. It is recommended to destroy it by unset().

So at the end of the first foreach, $v is a reference to the last element in the array. The next foreach's first iteration changes the value of $v (to the value of the first array element) which is a reference to the last element in the array, so it is changed.

$data = array("1" => "a", "2" => "b");
print_r($data);
foreach($data as $k=>&$v) {}
unset($v); // *** UNSET HERE ***
foreach($data as $k=>$v) {}
print_r($data);

Result:

Array
(
[1] => a
[2] => b
)
Array
(
[1] => a
[2] => b
)

foreach loop only outputs the last element from array

You don't need to foreach if you construct your query properly:

SELECT CONCAT(name, " ", lastname) AS fullName, typ AS class_type FROM table_name

Then just fetch all rows and return them:

$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);

How to get the last item of for loop

You can use array functions just like end() and/or current() and/or ect .
for ex :

foreach ($colors as $k => $v) {
if($v == end($colors)) {
// at last loop, code here
}
}

also can try to keep iterates number and check if is it the last one or not, but the first solution has better performance and keeps your code cleaner.

$iterateNumber = 0;
foreach ($colors as $k => $v) {
$iterateNumber++ ;
if($iterateNumber == count($colors)) {
// at last loop, code here
}
}

PHP : How to skip last element in foreach loop

Use a variable to track how many elements have been iterated so far and cut the loop when it reaches the end:

$count = count($array);

foreach ($array as $key => $val) {
if (--$count <= 0) {
break;
}

echo "$key = $val\n";
}

If you don't care about memory, you can iterate over a shortened copy of the array:

foreach (array_slice($array, 0, count($array) - 1) as $key => $val) {
echo "$key = $val\n";
}


Related Topics



Leave a reply



Submit