sidoco
sidoco

Reputation: 107

How can I get specific range of array just in specific range index by PHP?

I have an array like this (PHP Code):

$my_arr=array(0=>"Joe",1=>"Mike",2=>"Simo","Peter"=>"35", 3=>"Ben" , "Ben"=>"37", 4=>"Nik" , "Joe"=>"43");

I want just get values specific range of index and replace previous arrays values with these new values.Something like this:

$rang= 0-4 OR 0,1,2,3,4 //range of index values.
$my_arr= filtered array value in range index of $range.

I want get this result:

$my_arr=array(0=>"Joe",1=>"Mike",2=>"Simo", 3=>"Ben" , 4=>"Nik");

How should I do this?

Update:

I just want to separate the values of the array($my_arr) that are within the range of the specified number of indexes and everywhere in the array and replace all previous array($my_arr) values with these new values.

**

If there were not some of the indexes, Other indexes outside of the specified range for index numbers should not be replaced and only return values of indexes between 0 and 4($my_arr[0]....$my_arr[4]) , and if they don't have value leave empty or do not return something else

Upvotes: 0

Views: 1634

Answers (3)

sidoco
sidoco

Reputation: 107

I found a simple solution after several tests:

foreach($my_arr as $indx=>$val )
   {
       if(is_int($indx) && ($indx>=0 && $indx<=4))
       {
           $my_arr[$indx]= $val; 
        }
       else
       { continue; }

   }

Upvotes: 2

Nilesh Lathe
Nilesh Lathe

Reputation: 152

Try this code

$my_arr=array(0=>"Joe",1=>"Mike",2=>"Simo","Peter"=>"35", 3=>"Ben" , "Ben"=>"37", 4=>"Nik" , "Joe"=>"43");
$numerickeys = array_filter(array_keys($my_arr), 'is_int');
foreach($numerickeys as $num)
{
  $ar2[$num] = $my_arr[$num];
}
print_r($ar2);

Upvotes: 0

Ofir Baruch
Ofir Baruch

Reputation: 10356

array_slice

Extract a slice of the array

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

Since your array contains mixed keys, you should first sort it so the numeric keys would appear first.

According to your code:

ksort($my_arr, SORT_NATURAL);
$my_sliced_arr = array_slice($my_arr, 0, 4);

Output:

//var_dump($my_sliced_arr)
array(4) {
  [0]=>
  string(3) "Joe"
  [1]=>
  string(4) "Mike"
  [2]=>
  string(4) "Simo"
  [3]=>
  string(3) "Ben"
}

Upvotes: 2

Related Questions