Skip to content
Advertisement

PHP – Function echo not replace variable from a JSON object-string

I would like to print the value of the variable ‘$fruit’ directly with the php function echo.

If i use a string this work properly, but if the string is previous retrieve by a JSON object php not sostitute the variable with his value.

The above php code illustrate clearly the issue.

<?php

$json = '{

        "object_1":
            {
                "0": "banana",
                "1": "$fruit"

            }
            
        }';
            
$fruit = "mango";

$object_json = json_decode($json, false);

$var = $object_json->object_1->{1} ;

echo "$fruit "; // result: mango

echo $var; // result: $fruit, expected: mango

?>

Thank a lot four your help!

Advertisement

Answer

You have some conceptual failures within the code.

Check out this version of the same code that do what you expect:

<?php
$fruit = "mango";
$json = "{
        'object_1':
            {
                '0': 'banana',
                '1': '$fruit'

            }

        }";


$object_json = json_decode($json, false);

$var = $object_json->object_1->{1} ;

echo "$fruit"; // result: mango

echo $var; // result: mango
?>

One error on your code is that you reference a variable before that you defined it. The second one it’s that you can’t expect variable replacement with single-quoted strings. This happen with double-quoted strings.

Nevertheless, perhaps what do you want is to replace the variable as soon as you have the value of it (perhaps you get the value from a webservice, for example). In that case you will need to use some template library, or do it yourself with some regular expressions. With this method, you can do it in the way that you were trying to do it.

I hope that this help

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement