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
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"
?>
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]);
}
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.
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.
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);