我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
当前回答
这是一个结合了array_slice和implode的例子:
$arr = array(1, 2, 3);
echo implode(array_slice($arr, 0, 1));
// Outputs 1
/*---------------------------------*/
$arr = array(
'key_1' => 'One',
'key_2' => 'Two',
'key_3' => 'Three',
);
echo implode(array_slice($arr, 0, 1));
// Outputs One
其他回答
查找数组中的第一个和最后一个项:
// Get the first item in the array
print $array[0]; // Prints 1
// Get the last item in the array
print end($array);
有两个解决方案。
解决方案1 -使用钥匙。你没有说你不能用它。:)
<?php
// Get the first element of this array.
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
// Gets the first element by key
$result = $array[4];
// Expected result: string apple
assert('$result === "apple" /* Expected result: string apple. */');
?>
解决方案2 - array_flip() + key()
<?php
// Get first element of this array. Expected result: string apple
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
// Turn values to keys
$array = array_flip($array);
// You might thrown a reset in just to make sure
// that the array pointer is at the first element.
// Also, reset returns the first element.
// reset($myArray);
// Return the first key
$firstKey = key($array);
assert('$firstKey === "apple" /* Expected result: string apple. */');
?>
解决方案3 - array_keys()
echo $array[array_keys($array)[0]];
正如Mike指出的(最简单的方法):
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // Echoes "apple"
如果你想获取密钥:(重置后执行)
echo key($arr); // Echoes "4"
来自PHP的文档:
混合重置(数组|对象和$array);
描述:
reset()返回数组的内部指针指向第一个元素并返回第一个元素的值,如果数组为 空的。
我想象作者只是在寻找一种方法来获得一个数组的第一个元素后,从一些函数(mysql_fetch_row,例如),而不生成一个严格的“只有变量应该通过引用传递”。
如果是这样的话,这里描述的几乎所有方法都会得到这个消息…其中一些会使用大量额外的内存来复制一个数组(或其中的一部分)。避免它的一个简单方法是在调用任何这些函数之前内联赋值:
$first_item_of_array = current($tmp_arr = mysql_fetch_row(...));
// or
$first_item_of_array = reset($tmp_arr = func_get_my_huge_array());
这样就不会在屏幕上看到STRICT消息,也不会在日志中看到STRICT消息,也不会创建任何额外的数组。它既适用于索引数组,也适用于关联数组。
没有人建议使用ArrayIterator类:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'
绕过OP的参照规定。