I have an array of objects, any array in php. How do i skip the last element in the foreach iteration?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
There's various ways to do this.
If your array is a sequentially zero-indexed array, you could do:
If your array is an associative array, or otherwise not sequentially zero-indexed, you could do:
Use a variable to track how many elements have been iterated so far and cut the loop when it reaches the end:
If you don't care about memory, you can iterate over a shortened copy of the array:
If you don't want to delete the last array entry with pop, you could skip it like this
What you are trying to do will defeat the purpose of foreach loop. It is meant to loop through the entire array and make our job easy.
for ex: You can get the array size using COUNT function in php and then can use for loop and set the limit to arraysize-2, so the last array will be omitted