PHP Looping through half the array
So I have an array like this:
foreach($obj as $element){
//do something
}
But If the array contains mo开发者_开发知识库re than 50 elements (it is usually 100) I only want to loop through the first 50 of them, and then break the loop.
Clean way:
$arr50 = array_slice($obj, 0, 50);
foreach($arr50 as $element){
// $element....
}
Normal way (this will work only for arrays with numeric indexes and with asc order):
for($i=0; $i<50 && $i<count($obj); $i++){
$element = $obj[$i];
}
Or if you want to use foreach
you will have to use a counter:
$counter = 0;
foreach($obj as $element){
if( $counter == 50) break;
// my eyes!!! this looks bad!
$counter++;
}
Loop through half.
for($i=0; $i<count($obj)/2; $i++)
{
$element = $obj[$i];
// do something
}
or if you want first 50 elements always
$c = min(count($obj), 50);
for($i=0; $i<$c; $i++)
{
$element = $obj[$i];
// do something
}
Works for any array, not only for those with numeric keys 0, 1, ...
:
$i = 0;
foreach ($obj as $element) {
// do something
if (++$i == 50) {
break;
}
}
A neat alternative would be to make use of a couple of the SPL iterators like:
$limit = new LimitIterator(new ArrayIterator($obj), 0, 50);
foreach ($limit as $element) {
// ...
}
The identical procedural approach has already been mentioned, see answers using array_slice
.
for ($i = 0, $el = reset($obj); $i < count($obj)/2; $i++, $el = next($obj)) {
//$el contains the element
}
Keep it simple
$filtered = array_slice($array,0,((count($array)/2) < 50 && count($array) > 50 ? 50 : count($array)));
//IF array/2 is les that 50- while the array is greater then 50 then split the array to 50 else use all the values of the array as there less then 50 so it will not devide
foreach($filtered as $key => $row)
{
// I beliave in a thing called love.
}
Whats going on here
array_slice(
$array, //Input the whole array
0, //Start at the first index
(
count($array)/2 //and cut it down to half
)
)
for($i=0; $i < 50; $i++)
{
// work on $obj[$i];
}
Here's the most obvious approach to me:
$i = 0; // Define iterator
while($obj[$i]) // Loop until there are no more
{
trace($obj[$i]); // Do your action
$i++; // Increment iterator
}
This should work in all cases for half of an array regardless of length and whether it has numerical indexes or not:
$c = intval(count($array)/2);
reset($array);
foreach(range(1, $c) as $num){
print key($array)." => ".current($array)."\n";
next($array);
}
精彩评论