Can this PHP statement with a isset() check be simplified?












7















Needing to check whether the item exists in the array and either add to it or increase the value by the amount.



if(isset($this->_costRemovedByLineItem[$objectId])) {
$this->_costRemovedByLineItem[$objectId] += $amount;
}else{
$this->_costRemovedByLineItem[$objectId] = $amount;
}


I have a feeling this can be simplified.










share|improve this question























  • What version of PHP?

    – Nick
    Jan 30 at 2:40






  • 3





    Instead of trying to "simplify", go for code readability, you'll thank yourself later. Imho also go ahead and add a check for if is that property an array or not and add a handling for that scenario, cause php ain't letting you set an index for a boolean, now is it. 1 more vector of error squashed.

    – Mohd Abdul Mujib
    Jan 30 at 3:48


















7















Needing to check whether the item exists in the array and either add to it or increase the value by the amount.



if(isset($this->_costRemovedByLineItem[$objectId])) {
$this->_costRemovedByLineItem[$objectId] += $amount;
}else{
$this->_costRemovedByLineItem[$objectId] = $amount;
}


I have a feeling this can be simplified.










share|improve this question























  • What version of PHP?

    – Nick
    Jan 30 at 2:40






  • 3





    Instead of trying to "simplify", go for code readability, you'll thank yourself later. Imho also go ahead and add a check for if is that property an array or not and add a handling for that scenario, cause php ain't letting you set an index for a boolean, now is it. 1 more vector of error squashed.

    – Mohd Abdul Mujib
    Jan 30 at 3:48
















7












7








7


1






Needing to check whether the item exists in the array and either add to it or increase the value by the amount.



if(isset($this->_costRemovedByLineItem[$objectId])) {
$this->_costRemovedByLineItem[$objectId] += $amount;
}else{
$this->_costRemovedByLineItem[$objectId] = $amount;
}


I have a feeling this can be simplified.










share|improve this question














Needing to check whether the item exists in the array and either add to it or increase the value by the amount.



if(isset($this->_costRemovedByLineItem[$objectId])) {
$this->_costRemovedByLineItem[$objectId] += $amount;
}else{
$this->_costRemovedByLineItem[$objectId] = $amount;
}


I have a feeling this can be simplified.







php






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 30 at 2:05









lukemhlukemh

2,22262135




2,22262135













  • What version of PHP?

    – Nick
    Jan 30 at 2:40






  • 3





    Instead of trying to "simplify", go for code readability, you'll thank yourself later. Imho also go ahead and add a check for if is that property an array or not and add a handling for that scenario, cause php ain't letting you set an index for a boolean, now is it. 1 more vector of error squashed.

    – Mohd Abdul Mujib
    Jan 30 at 3:48





















  • What version of PHP?

    – Nick
    Jan 30 at 2:40






  • 3





    Instead of trying to "simplify", go for code readability, you'll thank yourself later. Imho also go ahead and add a check for if is that property an array or not and add a handling for that scenario, cause php ain't letting you set an index for a boolean, now is it. 1 more vector of error squashed.

    – Mohd Abdul Mujib
    Jan 30 at 3:48



















What version of PHP?

– Nick
Jan 30 at 2:40





What version of PHP?

– Nick
Jan 30 at 2:40




3




3





Instead of trying to "simplify", go for code readability, you'll thank yourself later. Imho also go ahead and add a check for if is that property an array or not and add a handling for that scenario, cause php ain't letting you set an index for a boolean, now is it. 1 more vector of error squashed.

– Mohd Abdul Mujib
Jan 30 at 3:48







Instead of trying to "simplify", go for code readability, you'll thank yourself later. Imho also go ahead and add a check for if is that property an array or not and add a handling for that scenario, cause php ain't letting you set an index for a boolean, now is it. 1 more vector of error squashed.

– Mohd Abdul Mujib
Jan 30 at 3:48














2 Answers
2






active

oldest

votes


















8














Something that will work in all versions of PHP:



@$this->_costRemovedByLineItem[$objectId] += $amount;


The @ (error control operator) will cause PHP to ignore the error caused by the non-existent index, create the element (with an empty value) and then add $amount to it, resulting in a value of $amount (as the empty value gets converted to 0 as a number).




Warning use of the @ operator could potentially make it harder to debug
your code, as it will hide error messages that you may have
needed to see (for example, even if $this doesn't exist, or there is
no object element called _costRemovedByLineItem, PHP will create
them along with the array). See the third case in my example code.




Alternatively in PHP7 you can use the Null Coalescing Operator:



$this->_costRemovedByLineItem[$objectId] = ($this->_costRemovedByLineItem[$objectId] ?? 0) + $amount;


And in PHP < 7 you can use the ternary operator



$this->_costRemovedByLineItem[$objectId] = (isset($this->_costRemovedByLineItem[$objectId]) ? $this->_costRemovedByLineItem[$objectId] : 0) + $amount;


A shorter example of each:



$amount = 4;
@$a[5] += $amount;
print_r($a);
$b[6] = ($b[6] ?? 0) + $amount;
print_r($b);
@$c->x[5] += $amount;
print_r($c);
$d[3] = (isset($d[3]) ? $d[3] : 0) + $amount;
print_r($d);


Output:



Array ( [5] => 4 ) 
Array ( [6] => 4 )
stdClass Object (
[x] => Array ( [5] => 4 )
)
Array ( [3] => 4 )


Demo on 3v4l.org






share|improve this answer


























  • Now that is nice

    – Siavas
    Jan 30 at 2:50






  • 4





    The null coalescing example is great imho, but the first example can be really problematic when debugging. I'd never recommend using @. What if _costRemovedByLineItem is deleted, or is an object. The code will fail without any error in anything under 7.1: 3v4l.org/pvvrX

    – Devon
    Jan 30 at 2:50













  • @Devon the failure in your demo occurs when _costRemovedByLineItem is an object, but if it is OPs code will also fail as they are trying to use it as an array too.

    – Nick
    Jan 30 at 3:11











  • That was my point. But in php 5.6 it's a silent failure, meaning you'd have no idea where the problem is. In a large project, you can never guarantee a property will remain the same long term. If someone changes the property or the property isn't what you think, the app may break and this makes it incredibly hard to track down.

    – Devon
    Jan 30 at 11:54











  • @Devon you are right, but we are talking about a hypothetical change of a variable from an array to an object which would require a complete code rewrite. As long as the variable remains an array it works fine in all versions of PHP 3v4l.org/ZhhhO

    – Nick
    Jan 30 at 12:12



















7














This method reduces it a bit, as you don't need the else statement or to assign amount twice.



if(!isset($this->_costRemovedByLineItem[$objectId])) {
$this->_costRemovedByLineItem[$objectId] = 0;
}
$this->_costRemovedByLineItem[$objectId] += $amount;





share|improve this answer
























    Your Answer






    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: "1"
    };
    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',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    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%2fstackoverflow.com%2fquestions%2f54432376%2fcan-this-php-statement-with-a-isset-check-be-simplified%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









    8














    Something that will work in all versions of PHP:



    @$this->_costRemovedByLineItem[$objectId] += $amount;


    The @ (error control operator) will cause PHP to ignore the error caused by the non-existent index, create the element (with an empty value) and then add $amount to it, resulting in a value of $amount (as the empty value gets converted to 0 as a number).




    Warning use of the @ operator could potentially make it harder to debug
    your code, as it will hide error messages that you may have
    needed to see (for example, even if $this doesn't exist, or there is
    no object element called _costRemovedByLineItem, PHP will create
    them along with the array). See the third case in my example code.




    Alternatively in PHP7 you can use the Null Coalescing Operator:



    $this->_costRemovedByLineItem[$objectId] = ($this->_costRemovedByLineItem[$objectId] ?? 0) + $amount;


    And in PHP < 7 you can use the ternary operator



    $this->_costRemovedByLineItem[$objectId] = (isset($this->_costRemovedByLineItem[$objectId]) ? $this->_costRemovedByLineItem[$objectId] : 0) + $amount;


    A shorter example of each:



    $amount = 4;
    @$a[5] += $amount;
    print_r($a);
    $b[6] = ($b[6] ?? 0) + $amount;
    print_r($b);
    @$c->x[5] += $amount;
    print_r($c);
    $d[3] = (isset($d[3]) ? $d[3] : 0) + $amount;
    print_r($d);


    Output:



    Array ( [5] => 4 ) 
    Array ( [6] => 4 )
    stdClass Object (
    [x] => Array ( [5] => 4 )
    )
    Array ( [3] => 4 )


    Demo on 3v4l.org






    share|improve this answer


























    • Now that is nice

      – Siavas
      Jan 30 at 2:50






    • 4





      The null coalescing example is great imho, but the first example can be really problematic when debugging. I'd never recommend using @. What if _costRemovedByLineItem is deleted, or is an object. The code will fail without any error in anything under 7.1: 3v4l.org/pvvrX

      – Devon
      Jan 30 at 2:50













    • @Devon the failure in your demo occurs when _costRemovedByLineItem is an object, but if it is OPs code will also fail as they are trying to use it as an array too.

      – Nick
      Jan 30 at 3:11











    • That was my point. But in php 5.6 it's a silent failure, meaning you'd have no idea where the problem is. In a large project, you can never guarantee a property will remain the same long term. If someone changes the property or the property isn't what you think, the app may break and this makes it incredibly hard to track down.

      – Devon
      Jan 30 at 11:54











    • @Devon you are right, but we are talking about a hypothetical change of a variable from an array to an object which would require a complete code rewrite. As long as the variable remains an array it works fine in all versions of PHP 3v4l.org/ZhhhO

      – Nick
      Jan 30 at 12:12
















    8














    Something that will work in all versions of PHP:



    @$this->_costRemovedByLineItem[$objectId] += $amount;


    The @ (error control operator) will cause PHP to ignore the error caused by the non-existent index, create the element (with an empty value) and then add $amount to it, resulting in a value of $amount (as the empty value gets converted to 0 as a number).




    Warning use of the @ operator could potentially make it harder to debug
    your code, as it will hide error messages that you may have
    needed to see (for example, even if $this doesn't exist, or there is
    no object element called _costRemovedByLineItem, PHP will create
    them along with the array). See the third case in my example code.




    Alternatively in PHP7 you can use the Null Coalescing Operator:



    $this->_costRemovedByLineItem[$objectId] = ($this->_costRemovedByLineItem[$objectId] ?? 0) + $amount;


    And in PHP < 7 you can use the ternary operator



    $this->_costRemovedByLineItem[$objectId] = (isset($this->_costRemovedByLineItem[$objectId]) ? $this->_costRemovedByLineItem[$objectId] : 0) + $amount;


    A shorter example of each:



    $amount = 4;
    @$a[5] += $amount;
    print_r($a);
    $b[6] = ($b[6] ?? 0) + $amount;
    print_r($b);
    @$c->x[5] += $amount;
    print_r($c);
    $d[3] = (isset($d[3]) ? $d[3] : 0) + $amount;
    print_r($d);


    Output:



    Array ( [5] => 4 ) 
    Array ( [6] => 4 )
    stdClass Object (
    [x] => Array ( [5] => 4 )
    )
    Array ( [3] => 4 )


    Demo on 3v4l.org






    share|improve this answer


























    • Now that is nice

      – Siavas
      Jan 30 at 2:50






    • 4





      The null coalescing example is great imho, but the first example can be really problematic when debugging. I'd never recommend using @. What if _costRemovedByLineItem is deleted, or is an object. The code will fail without any error in anything under 7.1: 3v4l.org/pvvrX

      – Devon
      Jan 30 at 2:50













    • @Devon the failure in your demo occurs when _costRemovedByLineItem is an object, but if it is OPs code will also fail as they are trying to use it as an array too.

      – Nick
      Jan 30 at 3:11











    • That was my point. But in php 5.6 it's a silent failure, meaning you'd have no idea where the problem is. In a large project, you can never guarantee a property will remain the same long term. If someone changes the property or the property isn't what you think, the app may break and this makes it incredibly hard to track down.

      – Devon
      Jan 30 at 11:54











    • @Devon you are right, but we are talking about a hypothetical change of a variable from an array to an object which would require a complete code rewrite. As long as the variable remains an array it works fine in all versions of PHP 3v4l.org/ZhhhO

      – Nick
      Jan 30 at 12:12














    8












    8








    8







    Something that will work in all versions of PHP:



    @$this->_costRemovedByLineItem[$objectId] += $amount;


    The @ (error control operator) will cause PHP to ignore the error caused by the non-existent index, create the element (with an empty value) and then add $amount to it, resulting in a value of $amount (as the empty value gets converted to 0 as a number).




    Warning use of the @ operator could potentially make it harder to debug
    your code, as it will hide error messages that you may have
    needed to see (for example, even if $this doesn't exist, or there is
    no object element called _costRemovedByLineItem, PHP will create
    them along with the array). See the third case in my example code.




    Alternatively in PHP7 you can use the Null Coalescing Operator:



    $this->_costRemovedByLineItem[$objectId] = ($this->_costRemovedByLineItem[$objectId] ?? 0) + $amount;


    And in PHP < 7 you can use the ternary operator



    $this->_costRemovedByLineItem[$objectId] = (isset($this->_costRemovedByLineItem[$objectId]) ? $this->_costRemovedByLineItem[$objectId] : 0) + $amount;


    A shorter example of each:



    $amount = 4;
    @$a[5] += $amount;
    print_r($a);
    $b[6] = ($b[6] ?? 0) + $amount;
    print_r($b);
    @$c->x[5] += $amount;
    print_r($c);
    $d[3] = (isset($d[3]) ? $d[3] : 0) + $amount;
    print_r($d);


    Output:



    Array ( [5] => 4 ) 
    Array ( [6] => 4 )
    stdClass Object (
    [x] => Array ( [5] => 4 )
    )
    Array ( [3] => 4 )


    Demo on 3v4l.org






    share|improve this answer















    Something that will work in all versions of PHP:



    @$this->_costRemovedByLineItem[$objectId] += $amount;


    The @ (error control operator) will cause PHP to ignore the error caused by the non-existent index, create the element (with an empty value) and then add $amount to it, resulting in a value of $amount (as the empty value gets converted to 0 as a number).




    Warning use of the @ operator could potentially make it harder to debug
    your code, as it will hide error messages that you may have
    needed to see (for example, even if $this doesn't exist, or there is
    no object element called _costRemovedByLineItem, PHP will create
    them along with the array). See the third case in my example code.




    Alternatively in PHP7 you can use the Null Coalescing Operator:



    $this->_costRemovedByLineItem[$objectId] = ($this->_costRemovedByLineItem[$objectId] ?? 0) + $amount;


    And in PHP < 7 you can use the ternary operator



    $this->_costRemovedByLineItem[$objectId] = (isset($this->_costRemovedByLineItem[$objectId]) ? $this->_costRemovedByLineItem[$objectId] : 0) + $amount;


    A shorter example of each:



    $amount = 4;
    @$a[5] += $amount;
    print_r($a);
    $b[6] = ($b[6] ?? 0) + $amount;
    print_r($b);
    @$c->x[5] += $amount;
    print_r($c);
    $d[3] = (isset($d[3]) ? $d[3] : 0) + $amount;
    print_r($d);


    Output:



    Array ( [5] => 4 ) 
    Array ( [6] => 4 )
    stdClass Object (
    [x] => Array ( [5] => 4 )
    )
    Array ( [3] => 4 )


    Demo on 3v4l.org







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 30 at 6:10

























    answered Jan 30 at 2:48









    NickNick

    38.3k132443




    38.3k132443













    • Now that is nice

      – Siavas
      Jan 30 at 2:50






    • 4





      The null coalescing example is great imho, but the first example can be really problematic when debugging. I'd never recommend using @. What if _costRemovedByLineItem is deleted, or is an object. The code will fail without any error in anything under 7.1: 3v4l.org/pvvrX

      – Devon
      Jan 30 at 2:50













    • @Devon the failure in your demo occurs when _costRemovedByLineItem is an object, but if it is OPs code will also fail as they are trying to use it as an array too.

      – Nick
      Jan 30 at 3:11











    • That was my point. But in php 5.6 it's a silent failure, meaning you'd have no idea where the problem is. In a large project, you can never guarantee a property will remain the same long term. If someone changes the property or the property isn't what you think, the app may break and this makes it incredibly hard to track down.

      – Devon
      Jan 30 at 11:54











    • @Devon you are right, but we are talking about a hypothetical change of a variable from an array to an object which would require a complete code rewrite. As long as the variable remains an array it works fine in all versions of PHP 3v4l.org/ZhhhO

      – Nick
      Jan 30 at 12:12



















    • Now that is nice

      – Siavas
      Jan 30 at 2:50






    • 4





      The null coalescing example is great imho, but the first example can be really problematic when debugging. I'd never recommend using @. What if _costRemovedByLineItem is deleted, or is an object. The code will fail without any error in anything under 7.1: 3v4l.org/pvvrX

      – Devon
      Jan 30 at 2:50













    • @Devon the failure in your demo occurs when _costRemovedByLineItem is an object, but if it is OPs code will also fail as they are trying to use it as an array too.

      – Nick
      Jan 30 at 3:11











    • That was my point. But in php 5.6 it's a silent failure, meaning you'd have no idea where the problem is. In a large project, you can never guarantee a property will remain the same long term. If someone changes the property or the property isn't what you think, the app may break and this makes it incredibly hard to track down.

      – Devon
      Jan 30 at 11:54











    • @Devon you are right, but we are talking about a hypothetical change of a variable from an array to an object which would require a complete code rewrite. As long as the variable remains an array it works fine in all versions of PHP 3v4l.org/ZhhhO

      – Nick
      Jan 30 at 12:12

















    Now that is nice

    – Siavas
    Jan 30 at 2:50





    Now that is nice

    – Siavas
    Jan 30 at 2:50




    4




    4





    The null coalescing example is great imho, but the first example can be really problematic when debugging. I'd never recommend using @. What if _costRemovedByLineItem is deleted, or is an object. The code will fail without any error in anything under 7.1: 3v4l.org/pvvrX

    – Devon
    Jan 30 at 2:50







    The null coalescing example is great imho, but the first example can be really problematic when debugging. I'd never recommend using @. What if _costRemovedByLineItem is deleted, or is an object. The code will fail without any error in anything under 7.1: 3v4l.org/pvvrX

    – Devon
    Jan 30 at 2:50















    @Devon the failure in your demo occurs when _costRemovedByLineItem is an object, but if it is OPs code will also fail as they are trying to use it as an array too.

    – Nick
    Jan 30 at 3:11





    @Devon the failure in your demo occurs when _costRemovedByLineItem is an object, but if it is OPs code will also fail as they are trying to use it as an array too.

    – Nick
    Jan 30 at 3:11













    That was my point. But in php 5.6 it's a silent failure, meaning you'd have no idea where the problem is. In a large project, you can never guarantee a property will remain the same long term. If someone changes the property or the property isn't what you think, the app may break and this makes it incredibly hard to track down.

    – Devon
    Jan 30 at 11:54





    That was my point. But in php 5.6 it's a silent failure, meaning you'd have no idea where the problem is. In a large project, you can never guarantee a property will remain the same long term. If someone changes the property or the property isn't what you think, the app may break and this makes it incredibly hard to track down.

    – Devon
    Jan 30 at 11:54













    @Devon you are right, but we are talking about a hypothetical change of a variable from an array to an object which would require a complete code rewrite. As long as the variable remains an array it works fine in all versions of PHP 3v4l.org/ZhhhO

    – Nick
    Jan 30 at 12:12





    @Devon you are right, but we are talking about a hypothetical change of a variable from an array to an object which would require a complete code rewrite. As long as the variable remains an array it works fine in all versions of PHP 3v4l.org/ZhhhO

    – Nick
    Jan 30 at 12:12













    7














    This method reduces it a bit, as you don't need the else statement or to assign amount twice.



    if(!isset($this->_costRemovedByLineItem[$objectId])) {
    $this->_costRemovedByLineItem[$objectId] = 0;
    }
    $this->_costRemovedByLineItem[$objectId] += $amount;





    share|improve this answer




























      7














      This method reduces it a bit, as you don't need the else statement or to assign amount twice.



      if(!isset($this->_costRemovedByLineItem[$objectId])) {
      $this->_costRemovedByLineItem[$objectId] = 0;
      }
      $this->_costRemovedByLineItem[$objectId] += $amount;





      share|improve this answer


























        7












        7








        7







        This method reduces it a bit, as you don't need the else statement or to assign amount twice.



        if(!isset($this->_costRemovedByLineItem[$objectId])) {
        $this->_costRemovedByLineItem[$objectId] = 0;
        }
        $this->_costRemovedByLineItem[$objectId] += $amount;





        share|improve this answer













        This method reduces it a bit, as you don't need the else statement or to assign amount twice.



        if(!isset($this->_costRemovedByLineItem[$objectId])) {
        $this->_costRemovedByLineItem[$objectId] = 0;
        }
        $this->_costRemovedByLineItem[$objectId] += $amount;






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 30 at 2:44









        DevonDevon

        23.7k42849




        23.7k42849






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54432376%2fcan-this-php-statement-with-a-isset-check-be-simplified%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

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            Npm cannot find a required file even through it is in the searched directory