Sunday, 24 September 2017

php - How to remove the first element of array without changing its key value?




I have an array in 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



$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...


Answer



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]);

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...