Markus Finell
Markus Finell

Reputation: 336

Prevent php from turning false into empty value

When using json_decode, boolean values of false gets turned into empty values. The json string I am using has values that can be empty, false, 1 or some text value, and I only want to use the fields that have values, even if the value is false. So when doing

$array = array();
foreach($obj as $key => $value){
  if($value != ''){
    $array[$key] = $value;
  }
}

fields with false values dont get saved into $array. Is there a way around that?

Update: When doing print_r($obj) all false values are empty. So I dont think the != is the problem. if I print_r the json string empty values are "null" and false values are "false", but when print_r-ing the json_decoded object both turn into empty values.

Upvotes: -1

Views: 1544

Answers (4)

Álvaro González
Álvaro González

Reputation: 146410

This question ranks high in Google so it's worth sharing some facts to avoid confusion:

  • Despite what the title may suggest, json_decode() does not have the ability to turn false into empty string, not even intentionally. If you've facing such case in your JSON-based application, the error must be somewhere else.

  • print_r() is not a reliable tool to inspect boolean variables because it casts everything to string, and PHP casts boolean false as empty string. Use var_dump() instead.

    $input = [true, false, ''];
    print_r($input);
    var_dump($input);
    
    Array
    (
        [0] => 1
        [1] => 
        [2] => 
    )
    array(3) {
      [0]=>
      bool(true)
      [1]=>
      bool(false)
      [2]=>
      string(0) ""
    }
    
  • PHP has two ≠ operators: loose (!=) and strict (!==). The former will apply type conversions to decide if values match, the latter will reject equality when types differ. You specifically want to avoid loose operator when you need to distinguish between null, false, empty string, number zero and string that starts with zero.

Upvotes: 1

Eimsas
Eimsas

Reputation: 492

Your false disappear because of

if($value != ''){

use

if($value !== ''){

because false in php is empty and your validation != stops false from passing

Upvotes: 2

Vitaliy Ryaboy
Vitaliy Ryaboy

Reputation: 478

change comparison from != to !==

$array = array();
foreach($obj as $key => $value){
  if($value !== ''){
    $array[$key] = $value;
  }
}

Upvotes: 1

Shira
Shira

Reputation: 6560

Use !== instead of != if you want to check for empty strings without considering other empty values.

Upvotes: 2

Related Questions