0

Is there a built-in function that gets the last element of a php array that doesn't require it to be referenced from a variable? end() and array_pop() work, but throw a notice.

What I have:

$example_url = '/demo/site/site.cfg';

$explosion = explode('/', $example_url);
if (end($explosion) == 'site.cfg') {
    //...
}

This throws Notice: Only variables should be passed by reference:

$example_url = '/demo/site/site.cfg';

if (end(explode('/', $example_url)) == 'site.cfg') {
    //...
}
kalkronline
  • 459
  • 2
  • 12
  • 1
    if i run this code i can't see any notice – Alberto Sinigaglia Jul 31 '20 at 20:05
  • are you suppressing errors? put this at the top to force error reporting. `error_reporting(-1); ini_set('display_errors', 1);` – kalkronline Jul 31 '20 at 20:08
  • which version of php are you using? – kalkronline Jul 31 '20 at 20:10
  • Does this answer your question? [What's the best way to get the last element of an array without deleting it?](https://stackoverflow.com/questions/3687358/whats-the-best-way-to-get-the-last-element-of-an-array-without-deleting-it) <- this basically gives you all existing ways to access the last element of an array. – Jeto Jul 31 '20 at 20:10
  • 2
    In your case I'd probably just go with [`basename`](https://www.php.net/manual/en/function.basename.php) though. – Jeto Jul 31 '20 at 20:14
  • @Jeto `basename` looks great, ill use that instead. `array_values(array_slice(explode('/', $example_url), -1))[0]` works, but I figured that there might be a cleaner way to do it. – kalkronline Jul 31 '20 at 20:21
  • 1
    Yeah I don't think there's a clean/easy way to grab the last element if you don't have a dedicated variable. Other than `basename`, I'd just go with the intermediate variable like in your first sample, can't hurt readability anyway. – Jeto Jul 31 '20 at 20:24

0 Answers0