Why must I assign the result of PHP's end() array function to a variable to operate on the result?

StackOverflow https://stackoverflow.com/questions/1633301

  •  06-07-2019
  •  | 
  •  

Question

I've tried to delete the possibly empty last entry of an array as follows but I get the error: "Can't use function return value in write context":

  if (empty(end($crontabEntryList))) {
    array_pop($crontabEntryList);
  }

If I first assign end's return value to a variable (as at the bottom) I am able to delete that last entry if empty. Per the manual entry for end() it "returns the value of the last element or FALSE for empty array." Through googling I've found a possible explanation: booleans are not "writable".

However then it would seem that this error gets returned, in my specific context, and possibly others documented here on SO, merely because it is possible that a boolean could be returned. Because, the array in my instance decidedly was not empty, and therefore rather than false, end() "returns the value of the last element".

Are my assumptions correct? In which case, isn't this inconsistent with the loosely typed nature of PHP? Or is it because the last element of the array is "not writable"? In which case, what precisely constitutes "write context" in PHP?

  $last = end($crontabEntryList);
  if (empty($last)) {
    array_pop($crontabEntryList);
  }
Was it helpful?

Solution

This has nothing to do with end() or "writability" of booleans.

empty() and isset() are not functions, they are language constructs.

From the docs for empty():

Note: empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

Again: only variables can be passed to empty().

OTHER TIPS

empty() is weird like that. I've just learned to accept it and work around it where possible (with the solution you provided).

If you're just trying to clear empty values from an array, try array_filter()

Can I suggest just using a negative check on the return value of end()? As I see it, end() either returns the value of the last element or FALSE if empty. So instead of using the extra code to create another variable to test with empty, just test the return of end():

/* Edited */
if(!(trim(end($crontabEntryList)))) {
   array_pop($crontabEntryList);
}

I have tested this on my system with an array of strings and it seems to have your desired effect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top