1
\$\begingroup\$

$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] => Array
        (
        )

    [1] => Array
        (
            [x] => 123
        )

    [2] => Array
        (
            [x] => 123
            [y] => 456
        )

    [3] => Array
        (
            [y] => 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?

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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.

\$\endgroup\$
0
1
\$\begingroup\$

I agree with @Gerrit0 that you should migrate to PHP7. Here is how I would do it:

$arr = [
    0 => [],
    1 => ['x' => 123],
    2 => ['x' => 123, 'y' => 456],
    3 => ['y' => 456]
];

$result = array_map(function ($v) {
    return sprintf('(%d,%d)', $v['x'] ?? 0, $v['y'] ?? 0);
}, $arr);

Result:

Array
(
    [0] => (0,0)
    [1] => (123,0)
    [2] => (123,456)
    [3] => (0,456)
)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.