Wednesday, 29 August 2018

Fill the assoc table in PHP with variables

I'm trying to fill an array in php with variables, but it's not working out at all. I'm using JSON and Javascript..

Anyway, here's the PHP code Javascript makes a call to.
<?php

$username = $_POST['username'];

    $json = '{
    "userdata": [
        {
            "first":"$username"
        },
        {
            "first":"Lester"
        },
        {
            "first":"Mannix"
        }
    ]
}';
echo $json;

?>

Now, the problem is, what I get back to Javascript is "$username", in plain text, not the variable's value.
Thanks in advance.

Variables aren't recognized in single quotes [doc]
Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
$json = '{
    "userdata": [
        {
            "first":"'.$username.'"
        },
        {
            "first":"Lester"
        },
        {
            "first":"Mannix"
        }
    ]
}';

0 comments:

Post a Comment