0

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.

1 Answer 1

1

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"}}}'
]
Sign up to request clarification or add additional context in comments.

1 Comment

The second one works best for me. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.