array_shift but preserve keys

前端 未结 4 1164
小鲜肉
小鲜肉 2021-01-17 09:41

My array looks like this:

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

How

4条回答
  •  温柔的废话
    2021-01-17 10:03

    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; 
    }
    

提交回复
热议问题