Validate array elements in PHP











up vote
1
down vote

favorite
1












$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?










share|improve this question




























    up vote
    1
    down vote

    favorite
    1












    $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?










    share|improve this question


























      up vote
      1
      down vote

      favorite
      1









      up vote
      1
      down vote

      favorite
      1






      1





      $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?










      share|improve this question















      $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?







      php php5






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 27 at 4:22









      Gerrit0

      2,9051522




      2,9051522










      asked Oct 27 at 3:21









      spicyramen

      265311




      265311






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          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.






          share|improve this answer





















          • Thanks for the great response. Now looks so clean!
            – spicyramen
            Oct 27 at 5:08


















          up vote
          1
          down vote













          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)
          )





          share|improve this answer








          New contributor




          nforced is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.


















            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f206361%2fvalidate-array-elements-in-php%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            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.






            share|improve this answer





















            • Thanks for the great response. Now looks so clean!
              – spicyramen
              Oct 27 at 5:08















            up vote
            1
            down vote



            accepted










            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.






            share|improve this answer





















            • Thanks for the great response. Now looks so clean!
              – spicyramen
              Oct 27 at 5:08













            up vote
            1
            down vote



            accepted







            up vote
            1
            down vote



            accepted






            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.






            share|improve this answer












            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.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Oct 27 at 4:46









            Gerrit0

            2,9051522




            2,9051522












            • Thanks for the great response. Now looks so clean!
              – spicyramen
              Oct 27 at 5:08


















            • Thanks for the great response. Now looks so clean!
              – spicyramen
              Oct 27 at 5:08
















            Thanks for the great response. Now looks so clean!
            – spicyramen
            Oct 27 at 5:08




            Thanks for the great response. Now looks so clean!
            – spicyramen
            Oct 27 at 5:08












            up vote
            1
            down vote













            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)
            )





            share|improve this answer








            New contributor




            nforced is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






















              up vote
              1
              down vote













              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)
              )





              share|improve this answer








              New contributor




              nforced is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.




















                up vote
                1
                down vote










                up vote
                1
                down vote









                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)
                )





                share|improve this answer








                New contributor




                nforced is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                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)
                )






                share|improve this answer








                New contributor




                nforced is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                share|improve this answer



                share|improve this answer






                New contributor




                nforced is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                answered Nov 13 at 12:15









                nforced

                414




                414




                New contributor




                nforced is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                New contributor





                nforced is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                nforced is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f206361%2fvalidate-array-elements-in-php%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Список кардиналов, возведённых папой римским Каликстом III

                    Deduzione

                    Mysql.sock missing - “Can't connect to local MySQL server through socket”