Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the first element of array without changing its key value? [duplicate]

Tags:

arrays

php

There's an array in php

<?php $array=array("a"=>"123","b"=>"234","c"=>"345"); array_shift($array); //array("0"=>"234","1"=>"345"); ?> 

If I use this function, then key value gets changed. I want my key value to remain the same. How can I remove first element without affecting array key values. My answer should be like

array("b"=>"234","c"=>"345"); 

Note:Please do not use foreach(); I want to do this by existing array functions in php

array_splice function is working for above array. But consider the below array

<?php $array = Array (     '39' => Array         (             'id' => '39',             'field_id' => '620'                     ),      '40' => Array         (             'id' => '40',             'field_id' => '620',             'default_value' => 'rrr',            ));  array_splice($array, 0, 1); print_r($array); ?> 

It is showing answer as follows:

Array ( [0] => Array ( [id] => 40 [field_id] => 620 [default_value] => rrr ) ) 

May I know the reason?? Will array_splice() work only for single dimensional array?? Now key value is reset...

like image 675
Ganesh Babu Avatar asked Sep 02 '13 16:09

Ganesh Babu


People also ask

How do I remove the first element from an array?

shift() The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

How do you remove the first two elements of an array?

To remove the first n elements from an array:Call the splice method on the array, passing it the start index and the number of elements to remove as arguments. For example, arr. splice(0,2) removes the first two elements from the array and returns a new array containing the removed elements.

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.


1 Answers

In case you do not know what the first item's key is:

// Make sure to reset the array's current index reset($array);  $key = key($array); unset($array[$key]); 
like image 164
aefxx Avatar answered Oct 02 '22 00:10

aefxx