steve
steve

Reputation: 879

Printing items in a PHP array

Is there a way to print a set number of items in an array?

So for example, print the first 3 items in $array. Then later on print the next 3 items in $array.

Any suggestions?

Thanks alot

Upvotes: 1

Views: 173

Answers (8)

Senad Meškin
Senad Meškin

Reputation: 13756

class ArrayHelper
{
   private static function printArray($from, $to, $array)
   {
     $_new = new Array();
     if($from <= count($array) && $to <= count($array)
     {
     for($i = $to; $i <= $from; $i++)
     {
         $_new[] = $array[$i];
     }
     }
     print_r($_new);
  }
}
$ar = array('One', 'Two', 'Three', 'Four');
ArrayHelper::printArray(0, 2);

Upvotes: 0

Tareq
Tareq

Reputation: 2006

Image that your array is as follows:

$ary = array('Apple', 'Banana', 'Mango', 'Coconut', 'Orange');

Now you want to print the first 3. This could be done as follows:

for($i=0;$i<3;$i++)
    echo $ary[$i];

For the Second 3 you can use the following:

for($i=3;$i<6;$i++)
   echo $ary[$i];

Upvotes: 0

Dan
Dan

Reputation: 537

function stepArray($array, $step) {
    static $location = 0;

    $started = $location;

    while ($location < ($started + $step) && isset($array[$location])) {
        echo $array[$location];

        $location++;
    }
}

That's just off the top of my head, and assumes the array is numbered sequentially. The static variable keeps track of where you were in the array, no matter how many times you call it. So calling

stepArray($array, 3);

Would print the first three elements, then

stepArray($array, 2);

Would print the next two, etc.

Upvotes: 0

Cyril N.
Cyril N.

Reputation: 39859

You can use array_slice to do the work :

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);         // return "c", "d", et "e"
$output = array_slice($input, -2, 1);     // return "d"
$output = array_slice($input, 0, 3);      // return "a", "b", et "c"
?>

Upvotes: 2

Sean Walsh
Sean Walsh

Reputation: 8344

for($i=0;$i<3;$i++) {
    echo $array[$i];
}

Then later,

for($i=0;$i<6;$i++) {
    echo $array[$i];
}

Upvotes: 0

Ryan Matthews
Ryan Matthews

Reputation: 1043

One thing I found a few months back was the Array Iterator Class

http://php.net/manual/en/class.arrayiterator.php

You should be able to use this to iterate over an array and pick up where you left off somewhere down the page.

Upvotes: 0

bmbaeb
bmbaeb

Reputation: 540

For the first group:

for ($i = 0; $i < 3; $i++)
echo $array[$i];

for the second group:

for ($i = 3; $i < 6; $i++)
echo $array[$i];

Upvotes: 1

Fosco
Fosco

Reputation: 38506

It's something you'd have to build, so depending on what your definition of 'print' is, it could be print_r, var_dump, or just echo, and you can use a function like this as just one example:

function printmyarraybythrees($array,$index) {
    for ($x = $index; $x < $index + 3; $x++) print_r($array[$x]);
}

Upvotes: 1

Related Questions