Home > other >  If statement inside PHP object
If statement inside PHP object

Time:11-07

Given the below code, how do I add an if statement inside obj so that the final PHP result does not display a field if it has a NULL value? For example, if id_info is NULL, then do not display "id":[id_info] in the actual PHP page? I couldn't find this info anywhere in the documentation.

<?php

$id_info =  ($db->query("SomeSQL query")->fetch_assoc())['id'];
$name_info = ....;
//some more queries

$obj = (object) ["id" => strval($id_info),
                 "Name" => (object) [
                                "eng_name" => strval($name_info)
            ]];
echo json_encode($obj);

?>

CodePudding user response:

Simply don't add it to the object in the first place:

$obj = [ "Name" => [ "eng_name" => strval($name_info) ] ];
if ($id_info != null) {
  $obj["id"] = strval($id_info);
}

CodePudding user response:

As by mentioned knittl you could check if a specific value is null and not add it to your object.

If it is necessary though to dynamically create objects withouth the hustle of checking. You have to use array_filter or any other custom filtering function for that.

I wrote a custom filtering function that accepts a deeply nested array and returns it back filtered.

function arrayFilter($inputArr){
    $output = null;

    if (is_array($inputArr)){
        foreach ($inputArr as $key=>$val){
            if(!$inputArr[$key]) continue;
            
            if (is_array($val)) {
                $tmpArr = arrayFilter($val);
                if($tmpArr) $output[$key] = array_filter($tmpArr);
                
            }
            else $output[$key] = $val;
            
            
        }
    } else {
        $output[$key] = $val;
    }
    
    return $output;
}

So, lets say you have a deeply nested object similar to the one you provided

$obj = (object) [
    "id" => null,
    "Name" => (object) [
        "eng_name" => strval('some name2'),
        "de_name" => null,
        "more" => (object) [
            "fr_name" => strval('some name3'),
            "ru_name" => null,
        ]
    ]
];

If you use the function like:

$filtered = arrayFilter(json_decode(json_encode($obj), true));

Your output will be something like the following:

{
   "Name":{
      "eng_name":"some name2",
      "more":{
         "fr_name":"some name3"
      }
    }
}
  • Related