0

My gut tells me that there is a better, perhaps one-line refactor for the following code:

if (isset($x))
{
    if (isset($y))
    {
        $z = array_merge($x,$y);
    }
    else
    {
        $z = $x;
    }
}
else
{
    $z = $y;
}

If I wasn't worried about warning errors, a simple array_merge($x,$y) would work, but I'd like to know a better way to do this. Thoughts?

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
pbarney
  • 2,529
  • 4
  • 35
  • 49

1 Answers1

6
$z = array_merge(
    isset($x) ? $x : array(),
    isset($y) ? $y : array()
);

This will return an empty array if $x and $y are not set. If only one is set, it will return that array. If both are set, it will return the result of array_merge() run on the arrays.

That is not quite the behavior of your code above, but I believe it is the behavior you intended. (I believe, in your code, that $z will not be an array if both $x and $y are not set.)

By the way, this code assumes that if $x and $y are set, that they are arrays. If that is not the case, you should either run is_array() on them to confirm they are arrays or use type juggling to make sure they are arrays when array_merge() runs.

Trott
  • 66,479
  • 23
  • 173
  • 212
  • Excellent answer, and returning a blank array helps me avoid checking is_array() later on. Thank you! – pbarney Dec 04 '11 at 03:40