I have an array:
我有一个数组:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
I would like to get the first element of this array. Expected result: string apple
我想要得到这个数组的第一个元素。预期结果:字符串苹果
One requirement: it cannot be done with passing by reference, so array_shift
is not a good solution.
一个要求是:不能通过引用传递,所以array_shift不是一个好的解决方案。
How can I do this?
我该怎么做呢?
35 个解决方案
#1
1053
Original answer, but costly (O(n)):
原始答案,但代价高昂(O(n)):
array_shift(array_values($array));
In O(1):
在O(1):
array_pop(array_reverse($array));
Edited with suggestions from comments for other use cases etc...
编辑的建议,从评论,其他用例等…
If modifying (in the sense of resetting array pointers) of $array
is not a problem, you might use:
如果修改(在重新设置数组指针的意义上)$array不是问题,您可以使用:
reset($array);
This should be theoretically more efficient, if a array "copy" is needed:
这在理论上应该更有效,如果需要一个数组“复制”:
array_shift(array_slice($array, 0, 1));
With PHP 5.4+ (but might cause an index error if empty):
使用PHP 5.4+(但如果是空的,可能会导致索引错误):
array_values($array)[0];
#2
703
As Mike pointed out (the easiest possible way):
正如迈克指出的(最简单的方法):
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
echo reset($arr); //echoes "apple"
If you want to get the key: (execute it after reset)
如果您想获得密钥:(重置后执行)
echo key($arr); //echoes "4"
From PHP's documentation:
从PHP的文档:
mixed reset ( array &$array );
混合复位(数组和$数组);
Description:
描述:
reset() rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.
reset() rewinds数组的内部指针指向第一个元素,返回第一个数组元素的值,如果数组为空,则返回FALSE。
#3
242
$first_value = reset($array); // First Element's Value
$first_key = key($array); // First Element's Key
Hope this helps. :)
希望这个有帮助。:)
#4
80
$arr = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // echoes 'apple'
If you don't want to lose the current pointer position, just create an alias for the array.
如果您不想失去当前的指针位置,只需为该数组创建一个别名。
#5
61
You can get Nth element with a language construct "list":
您可以使用语言构建“列表”获得第n个元素:
// 1st item
list($firstItem) = $yourArray;
// 1st item from an array that is returned from function
list($firstItem) = functionThatReturnsArray();
// 2nd item
list( , $secondItem) = $yourArray;
with array_keys function you can do the same for keys:
使用array_keys函数,您可以对密钥执行相同的操作:
list($firstKey) = array_keys($yourArray);
list(, $secondKey) = array_keys($yourArray);
#6
50
simply current($array)
can solve
当前美元(数组)可以解决
#7
46
PHP 5.4+:
PHP 5.4 +:
array_values($array)[0];
#8
25
Suppose:
假设:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
Just use:
只使用:
$array[key($array)]
to get first element or
得到第一个元素。
key($array)
to get first key.
第一个关键。
Or you can unlink the first if you want to remove it.
如果你想要删除它,你可以把它取消。
#9
17
Some arrays don't work with functions like list
, reset
or current
. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.
有些数组不使用list、reset或current等函数。例如,它们可能是“人造”数组——部分实现ArrayIterator。
If you want to pull the first value regardless of the array, you can short-circuit an iterator:
如果您想要获取第一个值,而不考虑数组,则可以对迭代器进行短路:
foreach($array_with_unknown_keys as $value) break;
Your value will then be available in $value
and the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).
您的值将在$value中可用,循环将在第一次迭代后中断。这比将一个潜在的大数组复制到像array_unshift(array_values($arr))这样的函数要有效得多。
You can grab the key this way too:
你也可以这样抓住钥匙:
foreach($array_with_unknown_keys as $key=>$value) break;
If you're calling this from a function, simply return early:
如果你从一个函数中调用这个函数,那么简单地返回:
function grab_first($arr) {
foreach($arr as $value) return $value;
}
#10
13
Simply do:
只是做的事:
array_shift(array_slice($array,0,1));
#11
11
I would do echo current($array)
.
我将做echo current($array)。
#12
10
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
foreach($arr as $first) break;
echo $first;
Output:
输出:
apple
#13
9
$array=array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$firstValue = each($array)[1];
This is much more efficient than array_values()
because the each()
function does not copy the entire array.
这比array_values()更有效,因为每个()函数不复制整个数组。
For more info see http://www.php.net/manual/en/function.each.php
有关更多信息,请参见http://www.php.net/manual/en/function.each.php。
#14
8
Most of these work! BUT for a quick single line (low resource) call:
大多数的工作!但是对于一个快速的单线(低资源)调用:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $array[key($array)];
// key($array) -> will return the first key (which is 4 in this example)
#15
8
$myArray = array (4 => 'apple', 7 => 'orange', 13 => 'plum');
$arrayKeys = array_keys($myArray);
// the first element of your array is:
echo $myArray[$arrayKeys[0]];
#16
7
A kludgy way is:
一个简单的方法是:
$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
function get_first ($foo) {
foreach ($foo as $k=>$v){
return $v;
}
}
print get_first($foo);
#17
7
From Laravel's helpers:
Laravel的助手:
function head($array)
{
return reset($array);
}
The array being passed by value to the function, the reset() affects the internal pointer of a copy of the array, it doesn't touch the original array. (note it returns false
if the array is empty)
通过值传递给函数的数组,reset()会影响数组副本的内部指针,它不会触及原始数组。(如果数组为空,则返回false)
Usage example:
使用的例子:
$data = ['foo', 'bar', 'baz'];
current($data); // foo
next($data); // bar
head($data); // foo
next($data); // baz
Also, here is an alternative. It's very marginally faster, but more interesting, it lets easily change the default value if the array is empty:
另外,这里还有一个选择。它的速度非常快,但更有趣的是,如果数组为空,它可以轻松地更改默认值:
function head($array, $default = null)
{
foreach ($array as $item) {
return $item;
}
return $default;
}
#18
7
Keep this simple! Lots of correct answers here, but to minimize all the confusion. These two work and reduce a lot of overhead.
保持这个简单!这里有很多正确的答案,但要尽量减少混乱。这两项工作减少了很多开销。
key($array)
= gets the first key of an arraycurrent($array)
= gets the first value of an array
key($array) =获取数组current($array)的第一个键值=获取数组的第一个值。
#19
4
I think using array_values would be your best bet here. You could return the value at index zero from the result of that function to get 'apple'.
我认为使用array_values是最好的选择。你可以从函数的结果返回“苹果”的值。
#20
4
This is a little late to the game, but I was presented with a problem where my array contained array elements as children inside it, and thus I couldn't just get a string representation of the first array element. By using PHP's current()
function, I managed this:
这有点晚了,但是我遇到了一个问题,我的数组中包含了数组元素作为子元素,因此我不能只得到第一个数组元素的字符串表示。通过使用PHP的current()函数,我管理如下:
<?php
$original = array(4 => array('one', 'two'), 7 => array('three', 'four'));
reset($original); // to reset the internal array pointer...
$first_element = current($original); // get the current element...
?>
Thanks to all the current solutions helped me get to this answer, I hope this helps someone sometime!
感谢所有的解决方案帮助我找到了这个答案,我希望这能帮助一个人!
#21
4
Get first element:
得到第一个元素:
array_values($arr)[0]
Get last element
得到最后一个元素
array_reverse($arr)[0]
#22
3
A small change to what Sarfraz posted is:
Sarfraz发布的一个小改动是:
$array = array(1, 2, 3, 4, 5);
$output = array_slice($array, 0, 1);
print_r ($output);
#23
3
Use:
使用:
$first = array_slice($array, 0, 1);
$val= $first[0];
By default, array_slice
does not preserve keys, so we can safely use zero as the index.
默认情况下,array_slice不保存密钥,因此我们可以安全地使用zero作为索引。
#24
3
This is not soo simple response in real world. Supost that we have this examples of possibles responses that you can find in some libraries.
在现实世界中,这并不是简单的反应。Supost,我们有这样的例子,你可以在一些图书馆找到答案。
$array1 = array();
$array2 = array(1,2,3,4);
$array3 = array('hello'=>'world', 'foo'=>'bar');
$array4 = null;
var_dump( 'reset1', reset($array1) );
var_dump( 'reset2', reset($array2) );
var_dump( 'reset3', reset($array3) );
var_dump( 'reset4', reset($array4) ); // warning
var_dump( 'array_shift1', array_shift($array1) );
var_dump( 'array_shift2', array_shift($array2) );
var_dump( 'array_shift3', array_shift($array3) );
var_dump( 'array_shift4', array_shift($array4) ); // warning
var_dump( 'each1', each($array1) );
var_dump( 'each2', each($array2) );
var_dump( 'each3', each($array3) );
var_dump( 'each4', each($array4) ); // warning
var_dump( 'array_values1', array_values($array1)[0] ); // Notice
var_dump( 'array_values2', array_values($array2)[0] );
var_dump( 'array_values3', array_values($array3)[0] );
var_dump( 'array_values4', array_values($array4)[0] ); // warning
var_dump( 'array_slice1', array_slice($array1, 0, 1) );
var_dump( 'array_slice2', array_slice($array2, 0, 1) );
var_dump( 'array_slice3', array_slice($array3, 0, 1) );
var_dump( 'array_slice4', array_slice($array4, 0, 1) ); // warning
list($elm) = $array1; //Notice
var_dump($elm);
list($elm) = $array2;
var_dump($elm);
list($elm) = $array3; // Notice
var_dump($elm);
list($elm) = $array4;
var_dump($elm);
Like you can see, we have several 'one line' solutions that work well in some cases, but not in all.
正如你所看到的,我们有几个“一行”的解决方案在某些情况下运行良好,但不是全部。
In my opinion, you have should that handler only with arrays.
在我看来,您应该只使用数组来处理这个处理程序。
Now talking about performance, assuming that we have always array, like this:
现在讨论性能,假设我们总是数组,像这样:
$elm = empty($array)? null : ...($array);
...you would use without errors:
$array[count($array)-1] ;
array_shift
reset
array_values
array_slice
array_shift is more fast that reset, that is more fast that [count()-1] and this three are more fast that array_values and array_slice
array_shift是更快的复位,这个速度更快(count()-1),而这三个更快,array_values和array_slice。
#25
3
Two solutions for you.
两种解决方案。
Solution 1 - Just use the key. You have not said, that you can not use it. :)
解决方案1 -使用关键字。你没有说过,你不能用它。:)
<?php
// get 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. */');
?>
Solution 2 - array_flip() + key()
解决方案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 an reset in
// just to make sure that the array pointer is at first element
// also reset return the first element
// reset($myArray);
// return first key
$firstKey = key($array);
assert('$firstKey === "apple" /* Expected result: string apple. */');
?>
Solution 3 - array_keys()
解决方案3 -中的()
echo $array[array_keys($array)[0]];
#26
2
Also worth bearing in mind the context in which you're doing this, as an exhaustive check can be expensive and not always necessary.
同样值得记住的是,你正在做的事情的上下文,作为一个详尽的检查可能是昂贵的,并不总是必要的。
For example, this solution works fine for the situation in which I'm using it (but obviously can't be relied on in all cases...)
例如,这个解决方案适用于我使用它的情况(但显然不能依赖于所有情况…)
/**
* A quick and dirty way to determine whether the passed in array is associative or not, assuming that either:<br/>
* <br/>
* 1) All the keys are strings - i.e. associative<br/>
* or<br/>
* 2) All the keys are numeric - i.e. not associative<br/>
*
* @param array $objects
* @return boolean
*/
private function isAssociativeArray(array $objects)
{
// This isn't true in the general case, but it's a close enough (and quick) approximation for the context in
// which we're using it.
reset($objects);
return count($objects) > 0 && is_string(key($objects));
}
#27
1
I like the "list" example, but "list" only works on the left-hand-side of an assignment. If we don't want to assign a variable, we would be forced to make up a temporary name, which at best pollutes our scope and at worst overwrites an existing value:
我喜欢“列表”的例子,但是“列表”只适用于任务的左侧。如果我们不想分配一个变量,我们将*临时起一个名字,它会在最大程度上污染我们的范围,并且在最坏的情况下重写一个现有的值:
list($x) = some_array();
var_dump($x);
The above will overwrite any existing value of $x, and the $x variable will hang around as long as this scope is active (the end of this function/method, or forever if we're in the top-level). This can be worked around using call_user_func and an anonymous function, but it's clunky:
上面的值将覆盖$x的任何现有值,并且$x变量将在这个范围是活动的时候挂起(这个函数/方法的结束,或者如果我们处于*)。可以使用call_user_func和匿名函数来解决这个问题,但它很笨拙:
var_dump(call_user_func(function($arr) { list($x) = $arr; return $x; },
some_array()));
If we use anonymous functions like this, we can actually get away with reset and array_shift, even though they use pass-by-reference. This is because calling a function will bind its arguments, and these arguments can be passed by reference:
如果我们使用这样的匿名函数,我们实际上可以使用reset和array_shift,即使它们使用了pass-by-reference。这是因为调用函数将绑定其参数,这些参数可以通过引用传递:
var_dump(call_user_func(function($arr) { return reset($arr); },
array_values(some_array())));
However, this is actually overkill, since call_user_func will perform this temporary assignment internally. This lets us treat pass-by-reference functions as if they were pass-by-value, without any warnings or errors:
但是,这实际上是过量的,因为call_user_func将在内部执行这个临时任务。这让我们可以将传递引用函数看作是按值传递的,没有任何警告或错误:
var_dump(call_user_func('reset', array_values(some_array())));
#28
1
Old post but anyway... I imagine the author just was looking for a way to get the first element of array after getting it from some function (mysql_fetch_row for example) without generating a STRICT "Only variables should be passed by reference". If it so, almos all ways described here will get this message... and some of them uses a lot of additional memory duplicating an array (or some part of it). An easy way to avoid it is just assigning the value inline before calling any of those functions:
旧邮政无论如何……我想,作者只是在寻找一种方法,从某些函数(例如mysql_fetch_row)中获取数组的第一个元素,而不生成严格的“仅通过引用传递的变量”。如果是这样,almos在这里描述的所有方法将得到这个消息…其中一些使用了大量的额外内存复制一个数组(或其中的一部分)。避免它的一种简单方法是在调用这些函数之前内联地分配值:
$first_item_of_array = current($tmp_arr = mysql_fetch_row(...));
// or
$first_item_of_array = reset($tmp_arr = func_get_my_huge_array());
This way you don't get the STRICT message on screen neither in logs and you don't create any additional arrays. It works with both indexed AND associative arrays
这样就不会在屏幕上得到严格的消息,也不会创建任何额外的数组。它与索引和关联数组一起工作。
#29
1
Use array_keys()
to access the keys of your associative array as a numerical indexed array, which is then again can be used as key for the array.
使用array_keys()来访问关联数组的键,作为一个数值索引数组,然后可以再次使用它作为数组的键。
When the solution is arr[0]
:
当解是arr[0]:
(Note, that since the array with the keys is 0-based index, the 1st element is index 0)
(注意,由于键的数组是基于0的索引,第1个元素是索引0)
You can use a variable and then subtract one, to get your logic, that 1 => 'apple'
.
你可以用一个变量,然后减去1,得到你的逻辑,1 => 'apple'。
$i = 1;
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[$i-1]];
Output:
输出:
apple
Well, for simplicity- just use:
为了简单起见,请使用:
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[0]];
Output:
输出:
apple
By the first method not just the first element, but can treat an associative array like an indexed array.
第一个方法不只是第一个元素,而是可以处理一个关联数组,比如索引数组。
#30
1
I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with array_keys()
or array_values()
, so I usually define this:
我不喜欢摆弄数组的内部指针,但是使用array_keys()或array_values()来构建第二个数组也很低效,所以我通常定义如下:
function array_first(array $f) {
foreach ($f as $v) {
return $v;
}
throw new Exception('array was empty');
}
#1
1053
Original answer, but costly (O(n)):
原始答案,但代价高昂(O(n)):
array_shift(array_values($array));
In O(1):
在O(1):
array_pop(array_reverse($array));
Edited with suggestions from comments for other use cases etc...
编辑的建议,从评论,其他用例等…
If modifying (in the sense of resetting array pointers) of $array
is not a problem, you might use:
如果修改(在重新设置数组指针的意义上)$array不是问题,您可以使用:
reset($array);
This should be theoretically more efficient, if a array "copy" is needed:
这在理论上应该更有效,如果需要一个数组“复制”:
array_shift(array_slice($array, 0, 1));
With PHP 5.4+ (but might cause an index error if empty):
使用PHP 5.4+(但如果是空的,可能会导致索引错误):
array_values($array)[0];
#2
703
As Mike pointed out (the easiest possible way):
正如迈克指出的(最简单的方法):
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
echo reset($arr); //echoes "apple"
If you want to get the key: (execute it after reset)
如果您想获得密钥:(重置后执行)
echo key($arr); //echoes "4"
From PHP's documentation:
从PHP的文档:
mixed reset ( array &$array );
混合复位(数组和$数组);
Description:
描述:
reset() rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.
reset() rewinds数组的内部指针指向第一个元素,返回第一个数组元素的值,如果数组为空,则返回FALSE。
#3
242
$first_value = reset($array); // First Element's Value
$first_key = key($array); // First Element's Key
Hope this helps. :)
希望这个有帮助。:)
#4
80
$arr = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // echoes 'apple'
If you don't want to lose the current pointer position, just create an alias for the array.
如果您不想失去当前的指针位置,只需为该数组创建一个别名。
#5
61
You can get Nth element with a language construct "list":
您可以使用语言构建“列表”获得第n个元素:
// 1st item
list($firstItem) = $yourArray;
// 1st item from an array that is returned from function
list($firstItem) = functionThatReturnsArray();
// 2nd item
list( , $secondItem) = $yourArray;
with array_keys function you can do the same for keys:
使用array_keys函数,您可以对密钥执行相同的操作:
list($firstKey) = array_keys($yourArray);
list(, $secondKey) = array_keys($yourArray);
#6
50
simply current($array)
can solve
当前美元(数组)可以解决
#7
46
PHP 5.4+:
PHP 5.4 +:
array_values($array)[0];
#8
25
Suppose:
假设:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
Just use:
只使用:
$array[key($array)]
to get first element or
得到第一个元素。
key($array)
to get first key.
第一个关键。
Or you can unlink the first if you want to remove it.
如果你想要删除它,你可以把它取消。
#9
17
Some arrays don't work with functions like list
, reset
or current
. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.
有些数组不使用list、reset或current等函数。例如,它们可能是“人造”数组——部分实现ArrayIterator。
If you want to pull the first value regardless of the array, you can short-circuit an iterator:
如果您想要获取第一个值,而不考虑数组,则可以对迭代器进行短路:
foreach($array_with_unknown_keys as $value) break;
Your value will then be available in $value
and the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).
您的值将在$value中可用,循环将在第一次迭代后中断。这比将一个潜在的大数组复制到像array_unshift(array_values($arr))这样的函数要有效得多。
You can grab the key this way too:
你也可以这样抓住钥匙:
foreach($array_with_unknown_keys as $key=>$value) break;
If you're calling this from a function, simply return early:
如果你从一个函数中调用这个函数,那么简单地返回:
function grab_first($arr) {
foreach($arr as $value) return $value;
}
#10
13
Simply do:
只是做的事:
array_shift(array_slice($array,0,1));
#11
11
I would do echo current($array)
.
我将做echo current($array)。
#12
10
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
foreach($arr as $first) break;
echo $first;
Output:
输出:
apple
#13
9
$array=array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$firstValue = each($array)[1];
This is much more efficient than array_values()
because the each()
function does not copy the entire array.
这比array_values()更有效,因为每个()函数不复制整个数组。
For more info see http://www.php.net/manual/en/function.each.php
有关更多信息,请参见http://www.php.net/manual/en/function.each.php。
#14
8
Most of these work! BUT for a quick single line (low resource) call:
大多数的工作!但是对于一个快速的单线(低资源)调用:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $array[key($array)];
// key($array) -> will return the first key (which is 4 in this example)
#15
8
$myArray = array (4 => 'apple', 7 => 'orange', 13 => 'plum');
$arrayKeys = array_keys($myArray);
// the first element of your array is:
echo $myArray[$arrayKeys[0]];
#16
7
A kludgy way is:
一个简单的方法是:
$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
function get_first ($foo) {
foreach ($foo as $k=>$v){
return $v;
}
}
print get_first($foo);
#17
7
From Laravel's helpers:
Laravel的助手:
function head($array)
{
return reset($array);
}
The array being passed by value to the function, the reset() affects the internal pointer of a copy of the array, it doesn't touch the original array. (note it returns false
if the array is empty)
通过值传递给函数的数组,reset()会影响数组副本的内部指针,它不会触及原始数组。(如果数组为空,则返回false)
Usage example:
使用的例子:
$data = ['foo', 'bar', 'baz'];
current($data); // foo
next($data); // bar
head($data); // foo
next($data); // baz
Also, here is an alternative. It's very marginally faster, but more interesting, it lets easily change the default value if the array is empty:
另外,这里还有一个选择。它的速度非常快,但更有趣的是,如果数组为空,它可以轻松地更改默认值:
function head($array, $default = null)
{
foreach ($array as $item) {
return $item;
}
return $default;
}
#18
7
Keep this simple! Lots of correct answers here, but to minimize all the confusion. These two work and reduce a lot of overhead.
保持这个简单!这里有很多正确的答案,但要尽量减少混乱。这两项工作减少了很多开销。
key($array)
= gets the first key of an arraycurrent($array)
= gets the first value of an array
key($array) =获取数组current($array)的第一个键值=获取数组的第一个值。
#19
4
I think using array_values would be your best bet here. You could return the value at index zero from the result of that function to get 'apple'.
我认为使用array_values是最好的选择。你可以从函数的结果返回“苹果”的值。
#20
4
This is a little late to the game, but I was presented with a problem where my array contained array elements as children inside it, and thus I couldn't just get a string representation of the first array element. By using PHP's current()
function, I managed this:
这有点晚了,但是我遇到了一个问题,我的数组中包含了数组元素作为子元素,因此我不能只得到第一个数组元素的字符串表示。通过使用PHP的current()函数,我管理如下:
<?php
$original = array(4 => array('one', 'two'), 7 => array('three', 'four'));
reset($original); // to reset the internal array pointer...
$first_element = current($original); // get the current element...
?>
Thanks to all the current solutions helped me get to this answer, I hope this helps someone sometime!
感谢所有的解决方案帮助我找到了这个答案,我希望这能帮助一个人!
#21
4
Get first element:
得到第一个元素:
array_values($arr)[0]
Get last element
得到最后一个元素
array_reverse($arr)[0]
#22
3
A small change to what Sarfraz posted is:
Sarfraz发布的一个小改动是:
$array = array(1, 2, 3, 4, 5);
$output = array_slice($array, 0, 1);
print_r ($output);
#23
3
Use:
使用:
$first = array_slice($array, 0, 1);
$val= $first[0];
By default, array_slice
does not preserve keys, so we can safely use zero as the index.
默认情况下,array_slice不保存密钥,因此我们可以安全地使用zero作为索引。
#24
3
This is not soo simple response in real world. Supost that we have this examples of possibles responses that you can find in some libraries.
在现实世界中,这并不是简单的反应。Supost,我们有这样的例子,你可以在一些图书馆找到答案。
$array1 = array();
$array2 = array(1,2,3,4);
$array3 = array('hello'=>'world', 'foo'=>'bar');
$array4 = null;
var_dump( 'reset1', reset($array1) );
var_dump( 'reset2', reset($array2) );
var_dump( 'reset3', reset($array3) );
var_dump( 'reset4', reset($array4) ); // warning
var_dump( 'array_shift1', array_shift($array1) );
var_dump( 'array_shift2', array_shift($array2) );
var_dump( 'array_shift3', array_shift($array3) );
var_dump( 'array_shift4', array_shift($array4) ); // warning
var_dump( 'each1', each($array1) );
var_dump( 'each2', each($array2) );
var_dump( 'each3', each($array3) );
var_dump( 'each4', each($array4) ); // warning
var_dump( 'array_values1', array_values($array1)[0] ); // Notice
var_dump( 'array_values2', array_values($array2)[0] );
var_dump( 'array_values3', array_values($array3)[0] );
var_dump( 'array_values4', array_values($array4)[0] ); // warning
var_dump( 'array_slice1', array_slice($array1, 0, 1) );
var_dump( 'array_slice2', array_slice($array2, 0, 1) );
var_dump( 'array_slice3', array_slice($array3, 0, 1) );
var_dump( 'array_slice4', array_slice($array4, 0, 1) ); // warning
list($elm) = $array1; //Notice
var_dump($elm);
list($elm) = $array2;
var_dump($elm);
list($elm) = $array3; // Notice
var_dump($elm);
list($elm) = $array4;
var_dump($elm);
Like you can see, we have several 'one line' solutions that work well in some cases, but not in all.
正如你所看到的,我们有几个“一行”的解决方案在某些情况下运行良好,但不是全部。
In my opinion, you have should that handler only with arrays.
在我看来,您应该只使用数组来处理这个处理程序。
Now talking about performance, assuming that we have always array, like this:
现在讨论性能,假设我们总是数组,像这样:
$elm = empty($array)? null : ...($array);
...you would use without errors:
$array[count($array)-1] ;
array_shift
reset
array_values
array_slice
array_shift is more fast that reset, that is more fast that [count()-1] and this three are more fast that array_values and array_slice
array_shift是更快的复位,这个速度更快(count()-1),而这三个更快,array_values和array_slice。
#25
3
Two solutions for you.
两种解决方案。
Solution 1 - Just use the key. You have not said, that you can not use it. :)
解决方案1 -使用关键字。你没有说过,你不能用它。:)
<?php
// get 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. */');
?>
Solution 2 - array_flip() + key()
解决方案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 an reset in
// just to make sure that the array pointer is at first element
// also reset return the first element
// reset($myArray);
// return first key
$firstKey = key($array);
assert('$firstKey === "apple" /* Expected result: string apple. */');
?>
Solution 3 - array_keys()
解决方案3 -中的()
echo $array[array_keys($array)[0]];
#26
2
Also worth bearing in mind the context in which you're doing this, as an exhaustive check can be expensive and not always necessary.
同样值得记住的是,你正在做的事情的上下文,作为一个详尽的检查可能是昂贵的,并不总是必要的。
For example, this solution works fine for the situation in which I'm using it (but obviously can't be relied on in all cases...)
例如,这个解决方案适用于我使用它的情况(但显然不能依赖于所有情况…)
/**
* A quick and dirty way to determine whether the passed in array is associative or not, assuming that either:<br/>
* <br/>
* 1) All the keys are strings - i.e. associative<br/>
* or<br/>
* 2) All the keys are numeric - i.e. not associative<br/>
*
* @param array $objects
* @return boolean
*/
private function isAssociativeArray(array $objects)
{
// This isn't true in the general case, but it's a close enough (and quick) approximation for the context in
// which we're using it.
reset($objects);
return count($objects) > 0 && is_string(key($objects));
}
#27
1
I like the "list" example, but "list" only works on the left-hand-side of an assignment. If we don't want to assign a variable, we would be forced to make up a temporary name, which at best pollutes our scope and at worst overwrites an existing value:
我喜欢“列表”的例子,但是“列表”只适用于任务的左侧。如果我们不想分配一个变量,我们将*临时起一个名字,它会在最大程度上污染我们的范围,并且在最坏的情况下重写一个现有的值:
list($x) = some_array();
var_dump($x);
The above will overwrite any existing value of $x, and the $x variable will hang around as long as this scope is active (the end of this function/method, or forever if we're in the top-level). This can be worked around using call_user_func and an anonymous function, but it's clunky:
上面的值将覆盖$x的任何现有值,并且$x变量将在这个范围是活动的时候挂起(这个函数/方法的结束,或者如果我们处于*)。可以使用call_user_func和匿名函数来解决这个问题,但它很笨拙:
var_dump(call_user_func(function($arr) { list($x) = $arr; return $x; },
some_array()));
If we use anonymous functions like this, we can actually get away with reset and array_shift, even though they use pass-by-reference. This is because calling a function will bind its arguments, and these arguments can be passed by reference:
如果我们使用这样的匿名函数,我们实际上可以使用reset和array_shift,即使它们使用了pass-by-reference。这是因为调用函数将绑定其参数,这些参数可以通过引用传递:
var_dump(call_user_func(function($arr) { return reset($arr); },
array_values(some_array())));
However, this is actually overkill, since call_user_func will perform this temporary assignment internally. This lets us treat pass-by-reference functions as if they were pass-by-value, without any warnings or errors:
但是,这实际上是过量的,因为call_user_func将在内部执行这个临时任务。这让我们可以将传递引用函数看作是按值传递的,没有任何警告或错误:
var_dump(call_user_func('reset', array_values(some_array())));
#28
1
Old post but anyway... I imagine the author just was looking for a way to get the first element of array after getting it from some function (mysql_fetch_row for example) without generating a STRICT "Only variables should be passed by reference". If it so, almos all ways described here will get this message... and some of them uses a lot of additional memory duplicating an array (or some part of it). An easy way to avoid it is just assigning the value inline before calling any of those functions:
旧邮政无论如何……我想,作者只是在寻找一种方法,从某些函数(例如mysql_fetch_row)中获取数组的第一个元素,而不生成严格的“仅通过引用传递的变量”。如果是这样,almos在这里描述的所有方法将得到这个消息…其中一些使用了大量的额外内存复制一个数组(或其中的一部分)。避免它的一种简单方法是在调用这些函数之前内联地分配值:
$first_item_of_array = current($tmp_arr = mysql_fetch_row(...));
// or
$first_item_of_array = reset($tmp_arr = func_get_my_huge_array());
This way you don't get the STRICT message on screen neither in logs and you don't create any additional arrays. It works with both indexed AND associative arrays
这样就不会在屏幕上得到严格的消息,也不会创建任何额外的数组。它与索引和关联数组一起工作。
#29
1
Use array_keys()
to access the keys of your associative array as a numerical indexed array, which is then again can be used as key for the array.
使用array_keys()来访问关联数组的键,作为一个数值索引数组,然后可以再次使用它作为数组的键。
When the solution is arr[0]
:
当解是arr[0]:
(Note, that since the array with the keys is 0-based index, the 1st element is index 0)
(注意,由于键的数组是基于0的索引,第1个元素是索引0)
You can use a variable and then subtract one, to get your logic, that 1 => 'apple'
.
你可以用一个变量,然后减去1,得到你的逻辑,1 => 'apple'。
$i = 1;
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[$i-1]];
Output:
输出:
apple
Well, for simplicity- just use:
为了简单起见,请使用:
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $arr[array_keys($arr)[0]];
Output:
输出:
apple
By the first method not just the first element, but can treat an associative array like an indexed array.
第一个方法不只是第一个元素,而是可以处理一个关联数组,比如索引数组。
#30
1
I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with array_keys()
or array_values()
, so I usually define this:
我不喜欢摆弄数组的内部指针,但是使用array_keys()或array_values()来构建第二个数组也很低效,所以我通常定义如下:
function array_first(array $f) {
foreach ($f as $v) {
return $v;
}
throw new Exception('array was empty');
}