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?
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).
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.
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 .
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With