aron n
aron n

Reputation: 597

how do I restrict this loop to a particular number?

below is from part of a loop

foreach($dataSet as $cType => $cPercentage){ echo $cType ."=". $cPercentage; }

this out put datas depend on array. what I want is I want to run this loop to only a particular number of times. say 8 times.

Upvotes: 1

Views: 229

Answers (7)

Nazariy
Nazariy

Reputation: 6088

If you want to truncate size of array you can use array_slice

so your code would look like this:

foreach(array_slice($dataSet, 0, 8) as $cType => $cPercentage){ echo $cType ."=". $cPercentage; }

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816334

You can also use another type of loop, e.g. while:

reset($dataSet);
$i = 8;
while((list($cType, $cPercentage) = each($dataSet)) && $i--) {
    echo $cType, ."=". $cPercentage;
}
reset($dataSet);

Reference: reset, each, list

Explanation:

each returns the key and value of the item the internal array pointer points to as array and advances the internal pointer. list assignes the array of key and value to two variables and returns the array. $i-- decrements the counter variable.
The loop will stop if either there are no elements in the array anymore (thus the array implicitly returned by list will be empty and evaluate to false) or if $i is 0.

Upvotes: 0

Xavier Barbosa
Xavier Barbosa

Reputation: 3947

This should work for numeric & associative arrays

$count = 0;
foreach($dataSet as $cType => $cPercentage) {
    echo $cType ."=". $cPercentage;
    if (++$count > 8) break;
}

Possibly, but not real advantage

$cappedArray = array_slice($dataSet, 0, 8, true);
foreach($cappedArray as $cType => $cPercentage) {
    echo $cType ."=". $cPercentage;
}

Upvotes: 0

Lylo
Lylo

Reputation: 1261

Try a while loop

$i = 0;
while($ds = each($dataSet) && $i < 8) {
   echo $ds['key']. '='.$ds['value'];
   $i++;
}

Upvotes: 0

Muhamad Bhaa Asfour
Muhamad Bhaa Asfour

Reputation: 1035

you can use the for loop to do this for you

Upvotes: 0

Nanne
Nanne

Reputation: 64399

If you mean by "to a number", do you mean like "8 times"? That you could do by

 $i=0;   
foreach($dataSet as $cType => $cPercentage){
    if($i==8){break;} 
    $i++;
    echo $cType ."=". $cPercentage; 
}

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101604

$nLoop = 0;
foreach($dataSet as $cType => $cPercentage){
  if ($nLoop++ == 8)
    break;
  echo $cType ."=". $cPercentage;
}

Upvotes: 4

Related Questions