So i have an array that contains 100 elements
foreach($obj as $element){
//do something
}
I want to loop through the first 50 but the problem is sometimes the $obj array maybe less then 50
So i have an array that contains 100 elements
foreach($obj as $element){
//do something
}
I want to loop through the first 50 but the problem is sometimes the $obj array maybe less then 50
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
}
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++;
}
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;
}
}
for ($i = 0, $el = reset($obj); $i < count($obj)/2; $i++, $el = next($obj)) {
//$el contains the element
}
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);
}
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
.
$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
)
)