简体   繁体   English

php获取数组的第一个值(关联或不关联)

[英]php get 1st value of an array (associative or not)

This might sounds like a silly question. 这可能听起来像一个愚蠢的问题。 How do I get the 1st value of an array without knowing in advance if the array is associative or not? 如果数组是否关联,如何在不事先知道的情况下获取数组的第一个值?

In order to get the 1st element of an array I thought to do this: 为了获得数组的第一个元素,我想这样做:

function Get1stArrayValue($arr) { return current($arr); }

is it ok? 好吗? Could it create issues if array internal pointer was moved before function call? 如果在函数调用之前移动了数组内部指针,它会产生问题吗? Is there a better/smarter/fatser way to do it? 有没有更好/更聪明/更胖的方式来做到这一点?

Thanks! 谢谢!

A better idea may be to use reset which "rewinds array's internal pointer to the first element and returns the value of the first array element" 一个更好的想法可能是使用reset “将数组的内部指针倒回到第一个元素并返回第一个数组元素的值”

Example: 例:

function Get1stArrayValue($arr) { return reset($arr); }

As @therefromhere pointed out in the comment below, this solution is not ideal as it changes the state of the internal pointer. 正如@therefromhere在下面的评论中指出的那样,这个解决方案并不理想,因为它改变了内部指针的状态。 However, I don't think it is much of an issue as other functions such as array_pop also reset it. 但是,我不认为这是一个很大的问题,因为像array_pop这样的其他函数也会重置它。
The main concern that it couldn't be used when iterating over an array isn't an problem as foreach operates on a copy of the array. 迭代数组时无法使用它的主要问题不是因为foreach在数组的副本上运行。 The PHP manual states: PHP手册说明:

Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. 除非引用了数组,否则foreach将对指定数组的副本进行操作,而不是数组本身。

This can be shown using some simple test code: 这可以使用一些简单的测试代码显示:

$arr = array("a", "b", "c", "d");
foreach ( $arr as $val ){
    echo reset($arr) . " - " . $val . "\n";
}

Result: 结果:

a - a
a - b
a - c
a - d

To get the first element for any array, you need to reset the pointer first. 要获取任何数组的第一个元素,您需要先重置指针。 http://ca3.php.net/reset http://ca3.php.net/reset

function Get1stArrayValue($arr) { 
  return reset($arr); 
}

If you don't mind losing the first element from the array, you can also use 如果你不介意丢失数组中的第一个元素,你也可以使用

array_shift() - shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. array_shift() - 关闭数组的第一个值并返回它,将数组缩短一个元素并将所有内容向下移动。 All numerical array keys will be modified to start counting from zero while literal keys won't be touched. 将修改所有数值数组键以从零开始计数,而不会触及文字键。

Or you could wrap the array into an ArrayIterator and use seek : 或者您可以将数组包装到ArrayIterator中并使用seek

$array = array("foo" => "apple", "banana", "cherry", "damson", "elderberry");
$iterator = new ArrayIterator($array);
$iterator->seek(0);
echo $iterator->current(); // apple

If this is not an option either, use one of the other suggestions. 如果这也不是一个选项,请使用其他建议之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM