Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip key index from a range of array's key in php

This is only for arrays with index number. For example i have this arrays;

$array = [
  "0" => "number 1",
  "1" => "number 2",
  "2" => "number 3",
  "3" => "number 4",
  "4" => "number 5",
  "5" => "number 6",
  "6" => "number 7",
  "7" => "number 8",
  "8" => "number 9"
];

I want to skip the loop from certain range of key indexes for example, skip the foreach if the number of index is from range 0 to 5. That means we can do just like this.

foreach($array as $key => $value){
   if(array_key_exist($key, range(0,5))
      continue;
   echo $value."<br/>"
}  

or we can using for... loop

for($ind = 0; $ind < count($array); $ind++){    
    if(array_key_exist($ind, range(0,5))
      continue;    
echo $arr[$ind]."<br/>" 
}

How could i skip the index without using continue or searching the array_key first ? sure the code above looks fine to me, but if i have a bunch of arrays keys and values, i think this is not a good choice.

like image 355
Gagantous Avatar asked Nov 25 '25 19:11

Gagantous


2 Answers

You can use array_diff as:

$wantKeys = array_diff(array_keys($array), range(1,5));

Now all you need is loop on the $wantKeys as:

foreach($wantKeys as $k) 
    echo $array[$k]; // only wanted values 

The same idea can be achieve by array_diff_keys:

$wantKeys = array_diff_key($array, array_flip(range(1,5)));
like image 167
dWinder Avatar answered Nov 27 '25 07:11

dWinder


You can get the slice of array from 5th index to rest,

$result = array_slice($array,5,count($array)-5, true);

array_slice — Extract a slice of the array

Note:

array_slice() will reorder and reset the integer array indices by default. This behaviour can be changed by setting preserve_keys to TRUE. String keys are always preserved, regardless of this parameter.

Demo.

like image 28
Rahul Avatar answered Nov 27 '25 08:11

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!