3

I have an array:

$array = array();
$array[0] = "string";
$array[1] = "string1";
$array[2] = "string2";
$array[3] = "string3";
...
$array[99] = "string99";
$array[100] = "string100";

If I want to work with all the values of the array:

foreach ($array as $key => $value)
{
    // Do something with the value
}

Depending on a condition, I might need to work with only portion of the array (for example 50-100). How do I extract key 50-100 from the array?

There is this way but it doesn't seem much efficient:

foreach ($array as $key => $value)
{
    if ($key > 49)
    {
        // Do something with the value
    }
}

Are there any better, more-efficient ways to do it?

Trondro Mulligan
  • 485
  • 3
  • 19

4 Answers4

3

Array in your question has numerical indexes, so you can use for loop. Then only keys in specified range will be processed. When you are using foreach all elements will be.

Example for range <50,100>

for($i=50; $i<=100; $i++) {
    //do something with $array[$i]
}

All others key wont be processed. You can also use functions like array_slice(), but it wont be such efficient.

Patryk Uszyński
  • 1,069
  • 1
  • 12
  • 20
2

PHP offers the function array_slice() for that:

An example using only the elements from key 50 upwards:

foreach (array_slice($array, 50) as $key => $value) {
    // Do something with the value
}

Using only 10 entries with an offset of 50, to elements 50-60:

foreach (array_slice($array, 50, 10) as $key => $value) {
    // Do something with the value
}

That function allows you to specify a length and an optional offset for the resulting part of the array.

See the documentation: http://php.net/manual/en/function.array-slice.php

arkascha
  • 41,620
  • 7
  • 58
  • 90
0

use array slice

 array_slice($array, 50, 100);
Nishant Nair
  • 1,999
  • 1
  • 13
  • 18
0
foreach ($array as $key => $value)
{
    if ($key < 50 OR $key > 101)
    {
        continue;
    }
}
Yasar Arafath
  • 605
  • 1
  • 9
  • 30
  • Won't I still be looping through the 100 keys? – Trondro Mulligan Jan 12 '17 at 12:11
  • Yes because `foreach` as is said, always will be iterating throught all elements of array. – Patryk Uszyński Jan 12 '17 at 12:15
  • If you want to loop only those values then you should use like this array_slice($array, 50, 100); – Yasar Arafath Jan 12 '17 at 12:17
  • 1
    @YasarArafath be very careful with using `OR`. It might not behave the way you think it does. Please read http://stackoverflow.com/questions/2803321/and-vs-as-operator for details. While in your answer it will work. If you're assigning values it could go really messy. – dokgu Jan 12 '17 at 16:33