array_shift but preserve keys

前端 未结 4 1135
小鲜肉
小鲜肉 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 09:59
    // 1 is the index of the first object to get
    // NULL to get everything until the end
    // true to preserve keys
    $arValues = array_slice($arValues, 1, NULL, true);
    
    0 讨论(0)
  • 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; 
    }
    
    0 讨论(0)
  • 2021-01-17 10:04

    This works fine for me...

    $array = array('1','2','3','4');
    
    reset($array);
    $key = key($array);
    $value = $array[$key];
    unset($array[$key]);
    
    var_dump($key, $value, $array, current($array));
    

    Output:

    int(0) 
    string(1) "1" 
    array(3) { [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" }
    string(1) "2"
    
    0 讨论(0)
  • 2021-01-17 10:12
    function array_shift_associative(&$arr){
        reset($arr);
        $return = array(key($arr)=>current($arr));
        unset($arr[key($arr)]);
        return $return; 
    }
    

    this function uses biziclop's method but returns a key=>value pair.

    0 讨论(0)
提交回复
热议问题