tags:

views:

168

answers:

9

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

+8  A: 

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
}
Adam
+1 for using min()
willoller
The first for won't work if the array contains, say, 60 elements.
Cristian
Only works for arrays with integer keys that start with 0 and whose keys are consecutive.
Artefacto
A: 
for($i=0; $i < 50; $i++)
{
  // work on $obj[$i];
}
willoller
Wont work on associative arrays.
RobertPitt
+7  A: 

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++;
}
Cristian
+1 for offering a variety of solutions.
Frank Farmer
-1 (though I don't really have the heart to really down vote you) for offering a variety of solution.
salathe
LOL... don't worry. That's the idea of SO. Anyway... why the -1?
Cristian
@Cristian (I still didn't actually down vote) purely because of offering up the other two alternatives after array_slice which gets the job done fine given no limitations preventing its use were listed in the question.
salathe
+7  A: 

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;
    }
}
Alexander Konstantinov
A: 
for ($i = 0, $el = reset($obj); $i < count($obj)/2; $i++, $el = next($obj)) {
    //$el contains the element
}
Artefacto
Ive never seen someone fit three functions in 1 loop iterator :/
RobertPitt
A: 

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
}
Peter Hanneman
this will end prematurely if any of the elements evaluates to false in the guard.
Artefacto
this made me smile.
RobertPitt
A: 

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);
}
pthayer
+2  A: 

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.

salathe
nice one... I feel like using Java `Iterator` interface!
Cristian
+1  A: 

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
  )
)
RobertPitt
What if the array has 60 elements? It will count just the first 30.
Cristian
Ok ive do a modification. heres the login`IF ( (array / 2 is less than 50) then get a whole 50 else use all the array )` its hard to explain it but should work.
RobertPitt
OK... that will do work. But, why don't just use `array_slice($array, 0, 50)`?
Cristian
i aint got a clue, i was just trying to give him the option of x/2, sooo i dunno, maybe I was wrong :/
RobertPitt