Frank
Frank

Reputation: 1345

PHP function : Return a object value if it's set

I'm trying to output a value of on object, but the value might not exist for some object records. How do I return the value without raising error "Undefined property: stdClass"?

For example, I have an object:

$obj = '[{"id":111,"value1":1,"value2":2},{"id":111,"value1":1}]';

value2 does not exist for the second element in the array, and I want to write a function to process each object in the array. Example:

function add($obj){
   $sum = 0;
   foreach($obj as $o){
      $sum += $o->value1;          

       if(isset($o->value2)){
          $sum += $o->value2;
       }
   }
   return $sum;
}

The if part is what I want to improve. There might be dozens of other values that don't exist for some object. I don't want to write if(isset($o->valueN)) every time.

Is there any other easier ways to code this to avoid the undefined property error?

Upvotes: 0

Views: 319

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94672

This will make sure you only add the occurances you want and only if they exist in the array.

ini_set('display_errors', 1); ini_set('log_errors',1); 

$obj = '[{"id":111,"value1":1,"value2":2},{"id":111,"value1":1}]';
$obj_array = json_decode($obj);

$required_occ = ['value1', 'value2'];

$sum = 0;

foreach ( $obj_array as $obj ) {
    foreach ( $required_occ as $occ ) {
        if ( isset($obj->$occ) ) {
            $sum += $obj->$occ;
        }
    }
}

echo $sum;

Result

4

Or to cut it down a bit, If youare using PHP7 and using the Null Coalescing Operator

ini_set('display_errors', 1); ini_set('log_errors',1); 

$obj = '[{"id":111,"value1":1,"value2":2},{"id":111,"value1":1}]';
$obj_array = json_decode($obj);

$required_occ = ['value1', 'value2'];
$sum = 0;
foreach ( $obj_array as $obj ) {
    foreach ( $required_occ as $occ ) {
        $sum += $obj->{$occ} ?? 0;
    }
}

echo $sum;

Result

4

Upvotes: 1

Robbie
Robbie

Reputation: 17710

Option 1: In php7 you can use the Null Coalescing Operator,

$sum += $o->value2 ?? 0;

Option 2: If you can create specific classes for the sub-items, then you can use magic method __get() so you only need to write isset once.

Option 3: Accept it? My code is littered with isset()s as it's a good reminder that something may or may not be set, but you know it and are handling it.

Upvotes: 2

Related Questions