array_shift但保留键

Shl*_*omo 13 php arrays

我的数组看起来像这样:

$arValues = array( 345 => "jhdrfr", 534 => "jhdrffr", 673 => "jhrffr", 234 => "jfrhfr" );
Run Code Online (Sandbox Code Playgroud)

如何删除数组的第一个元素,但保留数字键?因为array_shift我的整数键值改为0, 1, 2, ....

我尝试unset( $arValues[ $first ] ); reset( $arValues );继续使用第二个元素(现在是第一个),但它返回false.

我怎样才能做到这一点?

biz*_*lop 17

reset( $a );
unset( $a[ key($a)]);
Run Code Online (Sandbox Code Playgroud)

更有用的版本:

// 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 ]);
Run Code Online (Sandbox Code Playgroud)

功能:

// 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; 
}
Run Code Online (Sandbox Code Playgroud)

  • 因为我们特意要处理第一个元素.`reset()`将数组ponter移动到第一个元素,`key()`返回该元素的索引. (2认同)

pNr*_*Nre 7

// 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);
Run Code Online (Sandbox Code Playgroud)

  • 最好的答案在这里。不会乱用指针并且是可读的。 (4认同)

小智 7

当我需要这样做时,我使用了:

unset($a[array_key_first($a)]);
Run Code Online (Sandbox Code Playgroud)

array_key_first()于 2018 年底在 PHP 7.3 中引入/可用。我不需要处理我的用例的指针,但是您仍然可以reset($a)在需要时运行。我没有看到任何最近的答案,所以我想添加这个。

  • 干得好,用当前/现代功能填补了这一空白。我希望更多的人能做出这样有价值的尸检帖子。我也喜欢你的答案是接收紫外线——这是一个罕见的迹象,表明SO可以“正常工作”。 (2认同)