Jump to content

slicing an array based on the key value


php_joe

Recommended Posts

I have an array with numerical key values, but some keys are missing.

 

For example:

<?
$number[0] = 'zero';
$number[1] = 'one';
$number[2] = 'two';
$number[20] = 'twenty';
$number[30] = 'thirty';
$number[40] = 'fourty';
?>

 

I know I can use array_slice() but that won't return the values I want.

 

For example array_slice($number, 2) would return "two", "twenty", "thirty", "fourty", which would be right,

 

but array_slice($number, 10) would return nothing when what I want is "twenty", "thirty", "fourty"

 

Do I have to use foreach() to loop through the entire array and unset the values that I don't want? Or is there a better way?

 

Joe

Link to comment
https://forums.phpfreaks.com/topic/101155-slicing-an-array-based-on-the-key-value/
Share on other sites

The issue here is that it ignores key values, and simply uses the order the elements were declared... IE:

 

<?php

$number[5] = 'five';
$number[4] = 'four';
$number[3] = 'three';
$number[2] = 'two';
$number[1] = 'one';
$number[0] = 'zero';

print_r( array_slice($number, 2) );

?>

 

Returns

 

Array
(
    [0] => three
    [1] => two
    [2] => one
    [3] => zero
)

 

The reason it's returning an empty array is because there aren't 10 elements in your source array

If you use array_values() it will return a new array with the same values from your original array, but reindexed as you would expect:

<?php
$number[0] = 'zero';
$number[1] = 'one';
$number[2] = 'two';
$number[20] = 'twenty';
$number[30] = 'thirty';
$number[40] = 'fourty';
$newarray = array_values($number);
print_r($newarray);
?>

Array
{
   [0] => zero;
   [1] => one;
   [2] => two;
   [3] => twenty;
   [4] => thirty;
   [5] => fourty;
}

Just create a custom function:

 

<?php

function array_slice_from_index ($array, $index_value, $preserve_keys=false) {
 $return_array = array();
 foreach ($array as $key => $value) {
   if ($key>=$index_value) {
     $new_key = ($preserve_keys)?$key:count($return_array);
     $return_array[$key] = $value;
   }
 }
 return $return_array;
}

?>

 

Use the perserve_keys parameter as needed.

<?php

function array_slice_from_index ($array, $index_value, $preserve_keys=false) {
  $return_array = array();
  foreach ($array as $key => $value) {
    if ($key>=$index_value) {
      $new_key = ($preserve_keys)?$key:count($return_array);
      $return_array[$new_key] = $value;// <-- change this line
    }
  }
  return $return_array;
}
?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.