How can I remove the elements of the array from the beginning to the specified? for example, there is an array:

Array ( [title] => [keywords] => [category_id] => 23 [category] => 22 [subCategory] => 23 [typeCategory] => 25 [description] => [fullTextAdvert] => [price] => [rooms_apartament] => 0 [storey_apartament] => 0 [addPost] => ) 

I want to remove all items up to the [fullTextAdvert] element, inclusive. write 8 times (in this array the first 8 elements) unset ($ array ['element']) makes no sense, because there may be a different number of them

  • And to do so in a cycle is not an option? - entithat
  • How can this be done in a loop? I do not know for example! - vkt
  • It is possible without an explicit loop, although it will not work faster: $arr = array_slice($arr, array_search('fullTextAdvert', array_keys($arr)) + 1, null, true); - Deonis

2 answers 2

You can somehow.

 $array = [ 'title' => '', 'keywords' => '', 'category_id' => 23, 'category' => 22, 'subCategory' => 23, 'typeCategory' => 25, 'description' => '', 'fullTextAdvert' => '', 'price' => '', 'rooms_apartament' => 0, 'storey_apartament' => 0, 'addPost' => '' ]; // Проходим по массиву foreach ($array as $key => $value) { unset($array[$key]); // Удаляем элемент... if ($key == 'fullTextAdvert') { // Но если ключ равен fullTextAdvert, то прекращаем break; } } print_r($array); 

Displays:

 Array ( [price] => [rooms_apartament] => 0 [storey_apartament] => 0 [addPost] => ) 
  • thanks for the idea - vkt
  • @vkt, not at all :) - entithat

You can select values ​​from an array from a specified key using array_walk ():

 $array = [ 'title' => '', 'keywords' => '', 'category_id' => 23, 'category' => 22, 'subCategory' => 23, 'typeCategory' => 25, 'description' => '', 'fullTextAdvert' => '', 'price' => '', 'rooms_apartament' => 0, 'storey_apartament' => 0, 'addPost' => '' ]; array_walk($array, function($item, $k)use(&$new) { static $switch = false; $k != 'fullTextAdvert' ?: $switch = true; !$switch ?: $k == 'fullTextAdvert' ?: $new[$k] = $item; }, $array); 

The result will be in the $ new variable.

  • At first I thought so too, BUT as I wrote the first elements, it may not be 8 but 7 or 6. This is only in this example, the first elements are 8. And I need not to select the 8 first elements, but rather to exclude them from the array, delete - vkt
  • @vkt you need to delete everything first of the array and up to the fullTextAdvert key inclusive? I did not correctly write an example - Edward
  • Yes, I need to remove - vkt
  • thanks, you will need to familiarize yourself with the array_walk () function - vkt
  • one
    @entithat so not for anything :) - Edward