Validate array elements in PHP $elements is an array, which may contain 'x' or 'y' keys, I want to check if they exist, otherwise assign a 0. I'm looking for a clean way to validate it. I'm new to PHP, so I want to make sure my code is created according to PHP best practices.

Input array:

Array
(
    [0] =&gt; Array
        (
        )

    [1] =&gt; Array
        (
            [x] =&gt; 123
        )

    [2] =&gt; Array
        (
            [x] =&gt; 123
            [y] =&gt; 456
        )

    [3] =&gt; Array
        (
            [y] =&gt; 456
        )

)


Code:

foreach ($elements as $element) {
    $element_x = $element_y = 0;
    if (isset($element['x']))
        $element_x = $element['x'];
    if (isset($element['y']))
        $element_y = $element['y'];
    $results[] = sprintf('(%d,%d)', $element_x, $element_y);
}


Is there a cleaner way to do it?
First: Upgrade PHP!!! PHP 5.6 is losing security support on December 31st this year. Ref. All other PHP 5 versions are completely unsupported. You should be running PHP 7 today.

Once you've done that, you can use PHP 7's new null coalescing operator ?? to clean up the loop.

foreach ($elements as $element) {
    $results[] = sprintf('(%d,%d)', $element['x'] ?? 0, $element['y'] ?? 0);
}
unset($element);


Note that I've added unset($element) after the loop. You should always do this to avoid confusing behavior when using the same name in multiple loops. Take a look at the warning on PHP's documentation page for more info. You should also unset $element_x, and $element_y.

The PSR-2 style guide requires braces on control statements, style is a personal(/team) choice, but most people do agree with this rule:


  The body of each structure MUST be enclosed by braces. This standardizes how the structures look, and reduces the likelihood of introducing errors as new lines get added to the body. - PSR-2 Coding Style Guide


Other than this, I believe your code is about as clean as you can get. Good work! I'd probably go for $x instead of $element_x, but there's nothing wrong with your choice.