-3

Ran into a small PHP string problem which I was unable to find a solution to. I am trying to insert a variable value into the following string format, but it just inserts the variable, not the value of the varaible. Most likely a real easy fix, but I can't seem to figure it out.

$name ="michael";
   $datastring = '{
      "order": {
        "items": [
          {
            "reference": "webshop",
            "name": $name,
            "quantity": 1,
          }
        ]
       }
     }

How do I get it to replace $name with michael in this example here?

  • 4
    Does this answer your question? [PHP - concatenate or directly insert variables in string](https://stackoverflow.com/questions/5605965/php-concatenate-or-directly-insert-variables-in-string) – B001ᛦ Jul 06 '21 at 14:07

1 Answers1

2

You have to use double quoutes for variable interpolation to work in PHP. Because you are creating JSON it doesnt seem to be a solution so you should:

Create JSON structure as PHP array and use json_encode to transform to string
or
Use sprintf to interpolate variable in your string like:

$json = sprintf('{
      "order": {
        "items": [
          {
            "reference": "webshop",
            "name": "%s",
            "quantity": 1,
          }
        ]
       }
     }', "Value");
Code Spirit
  • 3,992
  • 4
  • 23
  • 34
  • Yes tried with double qoutes, brackets etc. no luck. Didn't even consider the sprintf command in this case. Excellent suggestion, thanks. – Michael Nielsen Jul 06 '21 at 18:50