2

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?

1
  • 1
    $cfg['x']['y']['z'] is basically ($cfg['x']['y'])['z'] - and after the second assignment, $cfg['x']['y'] is a string ("FALSE"), not an array. Any attempt to access it as an array is incorrect by definition; it's helpfulness of PHP that allow you to do it, but 'z' is treated as a zero index at a string. Commented Jun 26, 2015 at 14:28

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot John for your brief description

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.