Skip to content

Instantly share code, notes, and snippets.

@DavidGoodwin
Forked from Daniel15/gist:5991193
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidGoodwin/10023233 to your computer and use it in GitHub Desktop.
Save DavidGoodwin/10023233 to your computer and use it in GitHub Desktop.
<?php
/* Original effort: https://gist.github.com/Daniel15/5991193 */
function last($arr)
{
eval('list(' . str_repeat(',', count($arr) - 1) . '$result) = $arr;');
return $result;
}
/* An interesting challenge - what about : */
$list = array('a' => 'fish', 'b' => 'sausage', '&c' => 'whal=asdasd!@£123e');
/**
* Return the last element of an array AND it's associated key
* @param array (e.g. [ 23, 4, 5, 'fish' => 'beans' ] etc.)
*
* @return array last element of the array (as [$key => $value])
*/
function last_element($array) {
$string = http_build_query($array);
preg_match('/(&?([^&=]*)=([^&=]*))$/', $string, $matches);
$key = urldecode($matches[2]);
$value = urldecode($matches[3]);
return array($key => $value);
}
var_dump(last_element($list));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment