-2

How do i echo out a range from array $database for example data2 to data3?.

$database= array ("data1","data2","data3","data4");

Array_slice in this case will slove my problem.

$result = array_slice($database, 1, 2);
var_dump($result);

will output

array (size=2)
0 => string 'data2' (length=5)
1 => string 'data3' (length=5)

4 Answers4

3

If you have the range array_slice is what you will need.

http://www.php.net/manual/en/function.array-slice.php

In your scenario:

$database = array("data1","data2","data3","data4");
$result = array_slice($database, 1, 2);
var_dump($result);

If you didn't know the range, you can find it using array_search

http://uk3.php.net/array_search

In your scenario:

$database = array("data1","data2","data3","data4","data5","data6","data7","data8","data9");
$startKey = "data2";
$endKey = "data6";

$startRange = array_search($startKey, $database);
$endRange = array_search($endKey, $database);
$result = array_slice($database, $startRange, $endRange - $startRange + 1);
var_dump($result);

Careful though, if you have more than one of the same value, it will use the first one it finds in the array.

W

William George
  • 6,735
  • 3
  • 31
  • 39
0

You can use something like that:

$database= array ("data1","data2","data3","data4","data5","data6");

$start = 'data2';
$end = 'data4';
$started = false;
foreach ($database as $key=>$data){
    if ($data == $start) {
        $started = true;
    }
    if ($started == true) {
        echo $data;
    }
    if ($data == $end) {
        break;
    }
}

Here's a link to ideone: http://ideone.com/vxzMMq

  • Thanks this help alot, im kinda new into arrays, i allways prefered ifs but when project scales up its impossible to achive it with a fair ammout of code. – user3616064 May 13 '14 at 08:57
0

What if you use a counter

$database= array("data1","data2","data3","data4");
$i=0;

foreach ($database as $key=>$data){
$i++;
if ($i!=1 && $i!=4)
echo $data;

}

It's a kludge, but it works :P

Apeiron
  • 1,881
  • 2
  • 13
  • 21
0

You can use an if condition inside for each for checking the correct indices:

$database= array ("data1","data2","data3","data4");
$i=0;
foreach ($database as $key=>$data){
if($i>0 && $i<3)
 {
  echo $data;
 }
 $i++;
}
Azeez Kallayi
  • 2,567
  • 1
  • 15
  • 19