Home > front end >  (PHP) Problem inserting variables in array
(PHP) Problem inserting variables in array

Time:01-28

I'm having trouble inserting variables in an array. This is the array:

        [
            'body' => '{"data":{"attributes":{"details":{"card_number":"4343434343434345","exp_month":12,"exp_year":24,"cvc":"123"},"billing":{"name":"Test Man ","email":"[email protected]","phone":"1234567"},"type":"card"}}}',
            'headers' => [
                'Accept' => 'application/json',
                'Authorization' => 'Basic c2tfdGVzdF9mcUNRUmd4NVVUOEJhRHhEYnNHM2lOVm86',
                'Content-Type' => 'application/json',
            ],
        ]

What I need to be able to do is to replace the card_number, exp_month, exp_year, and so on with user submitted values. I have tried many ways to replace the values like this one:

        [
            'body' => '{"data":{"attributes":{"details":{"card_number":"{$request->cardNumber}","exp_month":{$request->cardMonth},"exp_year":{$request->cardyear},"cvc":"{$request->cardCVC}"},"billing":{"name":"{$request->name}","email":"{$request->email}","phone":"{$request->phone}"},"type":"card"}}}',
            'headers' => [
                'Accept' => 'application/json',
                'Authorization' => 'Basic c2tfdGVzdF9mcUNRUmd4NVVUOEJhRHhEYnNHM2lOVm86',
                'Content-Type' => 'application/json',
            ],
        ]

Unfortunately, the variables aren't being read. Any help is appreciated. Thanks.

CodePudding user response:

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details. https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

Either use double quoted strings and escape additional double quotes e.g:

[
'body' => "{\"data\":{\"attributes\":{\"details\":{\"card_number\":\"{$request->cardNumber}\",\"exp_month\":{$request->cardMonth},\"exp_year\":{$request->cardyear},\"cvc\":\"{$request->cardCVC}\"},\"billing\":{\"name\":\"{$request->name}\",\"email\":\"{$request->email}\",\"phone\":\"{$request->phone}\"},\"type\":\"card\"}}}"
]

Or using single-quoted and join multiple strings

[
'body' => '{"data":{"attributes":{"details":{"card_number":"' . $request->cardNumber . '","exp_month":' . $request->cardMonth . '},"exp_year":' . $request->cardyear . ',"cvc":"' . $request->cardCVC . '"},"billing":{"name":"' . $request->name . '}","email":"' . $request->email . '","phone":"' . $request->phone . '"},"type":"card"}}}'
]
  •  Tags:  
  • Related