John
John

Reputation: 291

Array not getting correct output in php

Learning php these days. At first sorry if its a dumb query.

<?php

$cfg['x']['y']['z'] = "TRUE"; 
$cfg['x']['y'] = "FALSE";

print_r($cfg['x']['y']['z']); //what to change here to get required output

?>

Output: F

But my expected output is TRUE

What should I change?

Upvotes: 2

Views: 45

Answers (1)

John Conde
John Conde

Reputation: 219804

Here $cfg['x']['y']['z'] no longer exists because you overwrote $cfg['x']['y'] which contained $cfg['x']['y']['z'].

 $cfg['x']['y'] = "FALSE";

Here you try to get the 'z' element of the $cfg['x']['y'] variable. It's a string since you put FALSE in quotes. 'z' is converted to zero by PHP's type juggling. So the 0 element of the string 'false is F

print_r($cfg['x']['y']['z']);

There's no real way to make this work the way you intend. You should be assigning FALSE to a new variable or turn $cfg['x']['y'] into an array so it can hold multiple values:

$cfg['x']['y'] = array(
    'z' = "TRUE",
    'newKey' = ""
);

FYI, if you intend to use "TRUE" and "FALSE" as boolean values you should not wrap them in quotes or else they are strings. As a result both "TRUE" and "FALSE" evaluate to true also due to PHP's type juggling.

Upvotes: 6

Related Questions