skip to Main Content

Is there any way a variable can be assigned from multiple procedures in one line?

For example:

$class_splits = explode("\", $class_name);
$short_class_name = $class_splits[count($class_splits) - 1] ?? null;

Translated to this pseudo code:

$short_class_name = explode("\", $class_name) => prev_result(count(prev_result) -1);

I don’t have big expectations on this as I know it looks too "high-level" but not sure if newer versions of PHP can handle this.

Thanks.

2

Answers


  1. You can use an assignment as an expression, then refer to the variable that was assigned later in the containing expression.

    $short_class_name = ($class_splits = explode("\", $class_name))[count($class_splits) - 1] ?? null;
    

    That said, I don’t recommend coding like this. If the goal was to avoid creating another variable, it doesn’t succeed at that. It just makes the whole thing more complicated and confusing.

    Login or Signup to reply.
  2. I believe you have an "X/Y Problem": your actual requirement seems to be "how to split a string and return just the last element", but you’ve got stuck thinking about a particular solution to that.

    As such, we can look at the answers to "How to get the last element of an array without deleting it?" To make it a one-line statement, we need something that a) does not require an argument by reference, and b) does not require the array to be mentioned twice.

    A good candidate looks like array_slice, which can return a single-element array with just the last element, from which we can then extract the string with [0]:

    $short_class_name = array_slice(explode("\", $class_name), -1)[0];
    

    Since we no longer need to call count(), we can avoid the problem of needing the same intermediate value in two places.

    Whether the result is actually more readable than using two lines of code is a matter of taste – remember that a program is as much for human use as for machine use.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search