Get the first element of an array - php

I have an array:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
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.
How can I do this?

Original answer, but costly (O(n)):
array_shift(array_values($array));
In O(1):
array_pop(array_reverse($array));
Other use cases, etc...
If modifying (in the sense of resetting array pointers) of $array is not a problem, you might use:
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):
array_values($array)[0];

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:
mixed reset ( array | object &$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.

$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key

current($array)
returns the first element of an array, according to the PHP manual.
Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.
So it works until you have re-positioned the array pointer, and otherwise you'll have to use reset() which ll rewind array and ll return first element of array
According to the PHP manual reset.
reset() rewinds array's internal pointer to the first element and returns the value of the first array element.
Examples of current() and reset()
$array = array('step one', 'step two', 'step three', 'step four');
// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"
//Forward the array pointer and then reset it
// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"
// reset pointer, start again on step one
echo reset($array) . "<br />\n"; // "step one"

$arr = $array = 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.

PHP 7.3 added two functions for getting the first and the last key of an array directly without modification of the original array and without creating any temporary objects:
array_key_first
array_key_last
Apart from being semantically meaningful, these functions don't even move the array pointer (as foreach would do).
Having the keys, one can get the values by the keys directly.
Examples (all of them require PHP 7.3+)
Getting the first/last key and value:
$my_array = ['IT', 'rules', 'the', 'world'];
$first_key = array_key_first($my_array);
$first_value = $my_array[$first_key];
$last_key = array_key_last($my_array);
$last_value = $my_array[$last_key];
Getting the first/last value as one-liners, assuming the array cannot be empty:
$first_value = $my_array[ array_key_first($my_array) ];
$last_value = $my_array[ array_key_last($my_array) ];
Getting the first/last value as one-liners, with defaults for empty arrays:
$first_value = empty($my_array) ? 'default' : $my_array[ array_key_first($my_array) ];
$last_value = empty($my_array) ? 'default' : $my_array[ array_key_last($my_array) ];

You can get the Nth element with a language construct, "list":
// First item
list($firstItem) = $yourArray;
// First item from an array that is returned from a function
list($firstItem) = functionThatReturnsArray();
// Second item
list( , $secondItem) = $yourArray;
With the array_keys function you can do the same for keys:
list($firstKey) = array_keys($yourArray);
list(, $secondKey) = array_keys($yourArray);

PHP 5.4+:
array_values($array)[0];

Some arrays don't work with functions like list, reset or current. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.
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)).
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;
}

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.

From Laravel's helpers:
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, and it doesn't touch the original
array (note it returns false if the array is empty).
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;
}
For the record, here is another answer of mine, for the array's last element.

Keep this simple! There are 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 array
current($array) gets the first value of an array
EDIT:
Regarding the comments below. The following example will output: string(13) "PHP code test"
$array = array
(
'1' => 'PHP code test',
'foo' => 'bar', 5 , 5 => 89009,
'case' => 'Random Stuff: '.rand(100,999),
'PHP Version' => phpversion(),
0 => 'ending text here'
);
var_dump(current($array));

Simply do:
array_shift(array_slice($array,0,1));

I would do echo current($array) .

$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
foreach($arr as $first) break;
echo $first;
Output:
apple

PHP 7.3 added two functions for getting the first and the last key of an array directly without modification of the original array and without creating any temporary objects:
array_key_first
array_key_last
"There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys(), but that may be rather inefficient. It is also possible to use reset() and key(), but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:"
<?php
if (!function_exists('array_key_first')) {
function array_key_first($arr) {
foreach($arr as $key => $unused) {
return $key;
}
return NULL;
}
}
if (!function_exists('array_key_last')) {
function array_key_last($arr) {
return array_key_first(array_reverse($arr, true));
}
}
?>

$myArray = array (4 => 'apple', 7 => 'orange', 13 => 'plum');
$arrayKeys = array_keys($myArray);
// The first element of your array is:
echo $myArray[$arrayKeys[0]];

$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.
For more info see http://www.php.net/manual/en/function.each.php

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);

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)
Although this works, and decently well, please also see my additional answer:
https://stackoverflow.com/a/48410351/1804013

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.

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
$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!

<?php
$arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
echo array_values($arr)[0]; // Outputs: Apple
?>
Other Example:
<?php
$arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
echo current($arr); // Outputs: Apple
echo reset($arr); // Outputs: Apple
echo next($arr); // Outputs: Ball
echo current($arr); // Outputs: Ball
echo reset($arr); // Outputs: Apple
?>

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'.

Two solutions for you.
Solution 1 - Just use the key. You have not said that you can not use it. :)
<?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. */');
?>
Solution 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. */');
?>
Solution 3 - array_keys()
echo $array[array_keys($array)[0]];

No one has suggested using the ArrayIterator class:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'
gets around the by reference stipulation of the OP.

I imagine the author just was looking for a way to get the first element of an 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, almost all the 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:
$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, nor in logs, and you don't create any additional arrays. It works with both indexed AND associative arrays.

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.
When the solution is arr[0]:
(Note, that since the array with the keys is 0-based index, the 1st
element is index 0)
You can use a variable and then subtract one, to get your logic, that 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.

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:
function array_first(array $f) {
foreach ($f as $v) {
return $v;
}
throw new Exception('array was empty');
}

This is not so simple response in the real world. Suppose that we have these examples of possible responses that you can find in some libraries.
$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 faster than reset, that is more fast than [count()-1], and these three are faster than array_values and array_slice.

Related

PHP rename key in Associative array

I've been searching through the articles on SO for this question and tried many of the solutions in my own code but it's not seeming to work.
I have the following array
$array[] = array("Order_no"=>$order_id,
"Customer"=>$customer_id,
"Product"=>$code_po,
"Product_description"=>$code_description,
"Position"=>$pos,
"Qty"=>$item_qty
);
I am looking to replace the "Order_no" key with a variable from a database query, lets assume in this case the variable is "new_name"
$new = "new_name";
$array[$new]=$array["Order_no"];
unset($array["Order_no"]);
print_r($array);
in the print_r statement I am getting the new_name coming through as the correct order number, but I am still seeing "Order_no" there also, which I shouldn't be seeing anymore.
Thanks.
This is your array:
Array
(
[0] => Array
(
[Customer] => 2
[Product] => 99
[Order_no] => 12345
)
)
One way to do it:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$i_arr = $arr[0];
$i_arr["new_name"] = $i_arr["Order_no"];
unset($i_arr["Order_no"]);
$arr[0] = $i_arr;
print_r($arr);
Another way:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$arr[0]["new_name"] = $arr[0]["Order_no"];
unset($arr[0]["Order_no"]);
print_r($arr);
To flatten your array out at any time:
<?php
$arr = $arr[0];
print_r($arr);
You are using extra level of array (by doing $array[] = ...).
You should do it with [0] as first index as:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
Live example: 3v4l
Another option is get ride of this extra level and init the array as:
$array = array("Order_no"=>$order_id, ...
As $array is also an array, you have to use index:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
The other answers will work for the first time you add to the array, but they will always work on the first item in the array. Once you add another it will not work, so get the current key:
$array[key($array)][$new] = $array[key($array)]["Order_no"];
unset($array[key($array)]["Order_no"]);
If you want the first one, then call reset($array); first.
Change your variable to
$array=array("Order_no"=>$order_id,"Customer"=>$customer_id,"Product"=>$code_po,"Product_description"=>$code_description,"Position"=>$pos,"Qty"=>$item_qty);
or change your code to
$new = "new_name";
$array[0][$new]=$array[0]["Order_no"];
unset($array["Order_no"]);
print_r($array);
Just be careful this would change the order of the array

Modify Current Value of Multidimensional Array

I have three arrays, say multiarray, valsarray, and otherarray. otherarray is a multidimensional array that supplies values to multiarray and valsarray, but besides that it is unimportant here. valsarray takes values from a subarray of each value in otherarray and multiarray takes straight values from otherarray, as demonstrated below:
foreach($otherarray as $other){
foreach($other as $sub){
$valsarray[] = $sub
}
$multiarray[] = array('Val1' => $other['Val1'], 'Val2' => $other['Val2']);
}
Now what I would like to do is append each key/value pair in valsarray to the current array entry of multiarray, to achieve a result similar to:
$multiarray = array('Val1' => $other['Val1'], 'Val2' => $other['Val2'],
'VALSARRAY_KEY1' => VALSARRAY_VALUE1, ..., 'VALSARRAY_KEYN' => VALSARRAY_VALUEN)
I have attempted to solve this using current in the following fashion:
foreach($valsarray as $key => $val){
current($multiarray)[$key] = $val;
}
But the multiarray remained unaltered. I may be misunderstanding how current works, or how to approach this problem, so any help or direction would be appreciated.
EDIT- EXAMPLE
otherarray = array(...prior array entries...,
array('Val1' => 'abc',
'Val2' => 'cde',
'Val3' => 'not important',
'Val4' => array(0 => 'subA', 1 => 'subB'),
...next array entries...);
BEFORE MERGE:
multiarray = array(...prior entries...,
array('Val1' => 'abc',
'Val2' => 'cde'));
valsarray = array(0 => 'subA', 1 => 'subB');
AFTER MERGE:
multiarray = array(...prior entries...,
array('Val1' => 'abc',
'Val2' => 'cde',
0 => 'subA',
1 => 'subB'));
So if multiarray was a regular array instead of a multidimensional one, I would do something like:
foreach($valsarray as $key => $val){
$multiarray[$key] = $val;
}
To achieve the end result.
I am not 100% sure what you are trying to accomplish a Minimal, Complete, and Verifiable example may help if I have misunderstood something.
It appears that the current() function does not work as you assume. (Or more specifically, the internal pointer.)
If you look at the example in the PHP documentation: Current(), you will see that for current($array) to change elements, you need to call next($array) or prev($array).
These function move the internal pointer of the array.
Note that in PHP 5, foreach loops use the internal pointer (and reset it when you start a loop), but in PHP 7, foreach loops do not use the internal pointer.
Anyway, here is my best guess at what could help you.
$valsarray_index = 0;
foreach ($otherarray as $other) {
$multiarray_value = array('Val1' => $other['Val1'], 'Val2' => $other['Val2']);
foreach ($other as $sub) {
$multiarray_value[$valsarray_index] = $sub;
// $multiarray_value["VALSARRAY_KEY" . $valsarray_index] = $sub;
$valsarray[] = $sub;
$valsarray_index += 1; // This stays in lockstep with the last index of $valsarray
}
$multiarray[] = $multiarray_value;
}
I am not exactly sure about what you want the final output to look like. If this produces incorrect information, then if would be helpful to provide some specific arrays for input and what you expect as output.

Which php functions act directly upon the variable? (like sort() )

Fer instance:
$fruits = array("lemon", "orange", "banana", "apple");
$sort = sort($fruits);
var_export($sort);
var_export($fruits);
returns
true
array ( 0 => 'apple', 1 => 'banana', 2 => 'lemon', 3 => 'orange', )
The sort() returns only a bool, if it worked or not. The function works on the variable, itself.
Whereas:
$s = 'thestring';
$trim = trim($s,'ing');
var_export($trim);
var_export($s);
returns:
'thestr'
'thestring'
So, what gives? Is there a rhyme or reason for this? Which functions act directly upon the variable?
edit:
'pass by reference', I see. Thusly:
function mytrimmer(&$string){
$string = trim($string,'ing');
return $string;
}
$s = 'thestring';
var_export(mytrimmer($s));
var_export($s);
returns
'thestr'
'thestr'
In addition to sort(), rsort() and shuffle() also act on the array variable supplied to the function.

Re-order the array order both key and value

Say I've got an array
[0]=>test
[2]=>example.
I want o/p as
[0]=>test
[1]=>example
In my first array
[1]=>NULL
I've tried to remove this and reorder so, I used array_filter() to remove the null value.
Now, how do I reorder the array?
If I understand what you need, I think array_values should help (it will return only the values in the array, reindexed from 0):
print_r( array_values($arr) );
Here's an example of this: http://codepad.org/q7dVqyVY
You might want to use merge:
$newArray = array_merge(array(),$oldArray);
$Array = array('0'=>'test,', '2'=>'example');
ksort($Array);
$ArrayTMP = array_values($Array);
or
$Array = array('0'=>'test,', '2'=>'example');
ksort($Array);
$ArrayTMP = array_merge ($Array,array());
Credit goes to: http://www.codingforums.com/archive/index.php/t-17794.html.
<?php
$a = array(0 => 1, 1 => null, 2 => 3, 3 => 0);
$r = array_values(
array_filter($a, function ($elem)
{
if ( ! is_null($elem))
return true;
})
);
// output:
array (
0 => 1,
1 => 3,
2 => 0,
)
?>
NOTE: I am using an anonymous callback function for array_filter. Anonymous callback only works in php 5.3+ and is the appropriate in this case (IMHO). For previous versions of php just define it as normal.

How to get last key in an array?

How can I get the last key of an array?
A solution would be to use a combination of end and key (quoting) :
end() advances array 's internal pointer to the last element, and returns its value.
key() returns the index element of the current array position.
So, a portion of code such as this one should do the trick :
$array = array(
'first' => 123,
'second' => 456,
'last' => 789,
);
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
var_dump($key);
Will output :
string 'last' (length=4)
i.e. the key of the last element of my array.
After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset() on the array to bring the pointer back to the beginning of the array.
Although end() seems to be the easiest, it's not the fastest. The faster, and much stronger alternative is array_slice():
$lastKey = key(array_slice($array, -1, 1, true));
As the tests say, on an array with 500000 elements, it is almost 7x faster!
Since PHP 7.3 (2018) there is (finally) function for this:
http://php.net/manual/en/function.array-key-last.php
$array = ['apple'=>10,'grape'=>15,'orange'=>20];
echo array_key_last ( $array )
will output
orange
I prefer
end(array_keys($myarr))
Just use : echo $array[count($array) - 1];
Dont know if this is going to be faster or not, but it seems easier to do it this way, and you avoid the error by not passing in a function to end()...
it just needed a variable... not a big deal to write one more line of code, then unset it if you needed to.
$array = array(
'first' => 123,
'second' => 456,
'last' => 789,
);
$keys = array_keys($array);
$last = end($keys);
As of PHP7.3 you can directly access the last key in (the outer level of) an array with array_key_last()
The definitively puts much of the debate on this page to bed. It is hands-down the best performer, suffers no side effects, and is a direct, intuitive, single-call technique to deliver exactly what this question seeks.
A rough benchmark as proof: https://3v4l.org/hO1Yf
array_slice() + key(): 1.4
end() + key(): 13.7
array_key_last(): 0.00015
*test array contains 500000 elements, microtime repeated 100x then averaged then multiplied by 1000 to avoid scientific notation. Credit to #MAChitgarha for the initial benchmark commented under #TadejMagajna's answer.
This means you can retrieve the value of the final key without:
moving the array pointer (which requires two lines of code) or
sorting, reversing, popping, counting, indexing an array of keys, or any other tomfoolery
This function was long overdue and a welcome addition to the array function tool belt that improves performance, avoids unwanted side-effects, and enables clean/direct/intuitive code.
Here is a demo:
$array = ["a" => "one", "b" => "two", "c" => "three"];
if (!function_exists('array_key_last')) {
echo "please upgrade to php7.3";
} else {
echo "First Key: " , key($array) , "\n";
echo "Last Key: " , array_key_last($array) , "\n";
next($array); // move array pointer to second element
echo "Second Key: " , key($array) , "\n";
echo "Still Last Key: " , array_key_last($array);
}
Output:
First Key: a
Last Key: c // <-- unaffected by the pointer position, NICE!
Second Key: b
Last Key: c // <-- unaffected by the pointer position, NICE!
Some notes:
array_key_last() is the sibling function of array_key_first().
Both of these functions are "pointer-ignorant".
Both functions return null if the array is empty.
Discarded sibling functions (array_value_first() & array_value_last()) also would have offered the pointer-ignorant access to bookend elements, but they evidently failed to garner sufficient votes to come to life.
Here are some relevant pages discussing the new features:
https://laravel-news.com/outer-array-functions-php-7-3
https://kinsta.com/blog/php-7-3/#array-key-first-last
https://wiki.php.net/rfc/array_key_first_last
p.s. If anyone is weighing up some of the other techniques, you may refer to this small collection of comparisons: (Demo)
Duration of array_slice() + key(): 0.35353660583496
Duration of end() + key(): 6.7495584487915
Duration of array_key_last(): 0.00025749206542969
Duration of array_keys() + end(): 7.6123380661011
Duration of array_reverse() + key(): 6.7875385284424
Duration of array_slice() + foreach(): 0.28870105743408
As of PHP >= 7.3 array_key_last() is the best way to get the last key of any of an array. Using combination of end(), key() and reset() just to get last key of an array is outrageous.
$array = array("one" => bird, "two" => "fish", 3 => "elephant");
$key = array_key_last($array);
var_dump($key) //output 3
compare that to
end($array)
$key = key($array)
var_dump($key) //output 3
reset($array)
You must reset array for the pointer to be at the beginning if you are using combination of end() and key()
Try using array_pop and array_keys function as follows:
<?php
$array = array(
'one' => 1,
'two' => 2,
'three' => 3
);
echo array_pop(array_keys($array)); // prints three
?>
It is strange, but why this topic is not have this answer:
$lastKey = array_keys($array)[count($array)-1];
I would also like to offer an alternative solution to this problem.
Assuming all your keys are numeric without any gaps,
my preferred method is to count the array then minus 1 from that value (to account for the fact that array keys start at 0.
$array = array(0=>'dog', 1=>'cat');
$lastKey = count($array)-1;
$lastKeyValue = $array[$lastKey];
var_dump($lastKey);
print_r($lastKeyValue);
This would give you:
int(1)
cat
You can use this:
$array = array("one" => "apple", "two" => "orange", "three" => "pear");
end($array);
echo key($array);
Another Solution is to create a function and use it:
function endKey($array){
end($array);
return key($array);
}
$array = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($array);
$arr = array('key1'=>'value1','key2'=>'value2','key3'=>'value3');
list($last_key) = each(array_reverse($arr));
print $last_key;
// key3
I just took the helper-function from Xander and improved it with the answers before:
function last($array){
$keys = array_keys($array);
return end($keys);
}
$arr = array("one" => "apple", "two" => "orange", "three" => "pear");
echo last($arr);
echo $arr(last($arr));
$array = array(
'something' => array(1,2,3),
'somethingelse' => array(1,2,3,4)
);
$last_value = end($array);
$last_key = key($array); // 'somethingelse'
This works because PHP moves it's array pointer internally for $array
The best possible solution that can be also used used inline:
end($arr) && false ?: key($arr)
This solution is only expression/statement and provides good is not the best possible performance.
Inlined example usage:
$obj->setValue(
end($arr) && false ?: key($arr) // last $arr key
);
UPDATE: In PHP 7.3+: use (of course) the newly added array_key_last() method.
Try this one with array_reverse().
$arr = array(
'first' => 01,
'second' => 10,
'third' => 20,
);
$key = key(array_reverse($arr));
var_dump($key);
Try this to preserve compatibility with older versions of PHP:
$array_keys = array_keys( $array );
$last_item_key = array_pop( $array_keys );

Categories