Reputation: 499
I have an array that submits values to an API. If I add in values manually it submits no problem but if I add a variable inside the array with the values it seems to treat the values as an array.
This works:
$post = array(
'email' => '[email protected]',
'first_name' => 'John',
);
This doesn't work:
$totals = "'first_name' => 'John', 'email' => '[email protected]'",
$post = array(
$totals
);
The error response from the API is:
[0] => 'first_name' => 'John', 'email' => '[email protected]',
Should there be another way to add my values to the API's array?
Upvotes: 0
Views: 74
Reputation: 9076
you need to wrap the key portion with square braces.This will work
$totals = "['first_name'] => 'John', ['email'] => '[email protected]'";
$post = array($totals);
print_r($post);
Upvotes: 1
Reputation: 72386
The first example is an array with two keys (email
and first_name
):
$post = array(
'email' => '[email protected]',
'first_name' => 'John',
);
Your second example is the same as this:
$post = array(
0 => "'first_name' => 'John', 'email' => '[email protected]'"
);
It contains only one entry, at key 0
. Its value looks like PHP code (but it's not). It is definitely not the same thing as the first example.
Apparently your question is how to handle arrays in PHP.
Read about PHP arrays. The documentation page explains how to create arrays using array()
, access array elements using square brackets and create/modify array elements using square brackets. PHP also provides a lot of functions to handle arrays.
After reading the docs you will be able to build and modify your array in multiple ways. For example:
$post = array();
$post['email'] = '[email protected]';
$post['first_name'] = 'John';
Upvotes: 1
Reputation: 462
You are basically trying to create an array from the String which is directly not possible
$totals = "'first_name' => 'John', 'email' => '[email protected]'";
It creates an string with the value 'first_name' => 'John', 'email' => '[email protected]'
Now your statement
$post = array($totals);
is basically assigning that string to $post array at zero index.
Upvotes: 1
Reputation: 9130
Why does the following not work?
$totals = "'first_name' => 'John', 'email' => '[email protected]'"
By placing double quotes "
around the values, you are assigning a String to $totals
and expecting it to create an array.
There are a few option to fix it. Option one
$post['first_name'] = 'John';
$post['email'] = '[email protected]';
Another option:
$post = array('first_name' => 'John', 'email' => '[email protected]');
And another option:
$totals = array('first_name' => 'John', 'email' => '[email protected]');
$post = $totals;
As I'm not sure where the $totals
values are coming from, there could be many more options.
Upvotes: 2
Reputation: 353
Try this....
$totals = array();
$totals['first_name'] = 'John';
$totals['email'] = '[email protected]';
$post = $totals;
print_r($post);
Upvotes: 1