Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_shift but preserve keys

Tags:

arrays

php

My array looks like this:

$arValues = array( 345 => "jhdrfr", 534 => "jhdrffr", 673 => "jhrffr", 234 => "jfrhfr" );

How can I remove the first element of an array, but preserve the numeric keys? Since array_shift changes my integer key values to 0, 1, 2, ....

I tried using unset( $arValues[ $first ] ); reset( $arValues ); to continue using the second element (now first), but it returns false.

How can I achieve this?

like image 871
Shlomo Avatar asked Sep 30 '13 17:09

Shlomo


People also ask

What is the use of array_shift () function?

The array_shift() function removes the first element from an array, and returns the value of the removed element. Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).

How do I remove the first key from an array?

To remove the first element or value from an array, array_shift() function is used. This function also returns the removed element of the array and returns NULL if the array is empty.

How to remove first row in array php?

Answer: Use the PHP array_shift() function You can use the PHP array_shift() function to remove the first element or value from an array. The array_shift() function also returns the removed value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL .

How to remove first element from array in laravel?

You can use shift() to get and remove the first item of a Laravel collection. The shift method returns that first removed from a collection item.


1 Answers

reset( $a );
unset( $a[ key($a)]);

A bit more useful version:

// rewinds array's internal pointer to the first element
// and returns the value of the first array element. 
$value = reset( $a );

// returns the index element of the current array position
$key   = key( $a );

unset( $a[ $key ]);

Functions:

// returns value
function array_shift_assoc( &$arr ){
  $val = reset( $arr );
  unset( $arr[ key( $arr ) ] );
  return $val; 
}

// returns [ key, value ]
function array_shift_assoc_kv( &$arr ){
  $val = reset( $arr );
  $key = key( $arr );
  $ret = array( $key => $val );
  unset( $arr[ $key ] );
  return $ret; 
}
like image 50
biziclop Avatar answered Sep 22 '22 06:09

biziclop