How can I pass one or more variables of type array to another page via $_GET?
I always passed variable values in the form ?a=1&b=2&c=3
What about passing a=[1,2,3] ?
Do I need to write a for loop and append all the values?
Thanks
You can use the [] syntax to pass arrays through _GET:
?a[]=1&a[]=2&a[]=3
PHP understands this syntax, so $_GET['a'] will be equal to array(1, 2, 3).
You can also specify keys:
?a[42]=1&a[foo]=2&a[bar]=3
Multidimentional arrays work too:
?a[42][b][c]=1&a[foo]=2
http_build_query() does this automatically:
http_build_query(array('a' => array(1, 2, 3))) // "a[]=1&a[]=2&a[]=3"
http_build_query(array(
'a' => array(
'foo' => 'bar',
'bar' => array(1, 2, 3),
)
)); // "a[foo]=bar&a[bar][]=1&a[bar][]=2&a[bar][]=3"
An alternative would be to pass json encoded arrays:
?a=[1,2,3]
And you can parse a with json_decode:
$a = json_decode($_GET['a']); // array(1, 2, 3)
And encode it again with json_encode:
json_encode(array(1, 2, 3)); // "[1,2,3]"
Dont ever use serialize() for this purpose. Serialize allows to serialize objects, and there is ways to make them execute code. So you should never deserialize untrusted strings.
You can pass an associative array to http_build_query() and append the resulting string as the query string to the URL. The array will automatically be parsed by PHP so $_GET on the receiving page will contain an array.
Example
$query_str = http_build_query(array(
'a' => array(1, 2, 3)
));
$city_names = array(
'delhi',
'mumbai',
'kolkata',
'chennai'
);
$city_query = http_build_query(array('city' => $city_names));
this will give you:
city[0]=delhi&city[1]=mumbai&city[2]=kolkata&city[3]=chennai
if you want to encode the brackets also then use the below code:
$city_query = urlencode(http_build_query(array('city' => $city_names)));
Output:
city%255B0%255D%3Ddelhi%26city%255B1%255D%3Dmumbai .....
Reference: http_build_query, urlencode
Just repeat your $_GET variables like this: name=john&name=lea
This gives you an array.
I used to believe it would be overwritten!
Related
Is there a standard PHP function that changes an associative array's index names?
$a1 = array('one'=>1,'two'=>2,'three'=>3);
$new_index_names = array('one'=>'ono','two'=>'dos','three'=>'tres');
$a2 = change_index_names($a1,$new_index_names);
print_r($a2);
// $a2 should have the index names changed accordingly and look like this:
// array('ono'=>1,'dos'=>2,'tres'=>3)
EDIT
Please note that the function needs to know the mappings to the new index names. Meaning, in $new_index_names array provides the mappings. So again, it needs to know that 'ono' is the new index name for 'one'.
EDIT
I know you guys can come up with your own solution, i was wondering there is a standard PHP function that already does this.
EDIT
There are several situations where changing index names would help:
1) separates post value names to generic/internal names so you can separate
your backend code from front-end code.
2) say for instance you have two arrays from post that need to go through the
same exact process, except both arrays although mean/contain same exact type
of values/order/structure, they're index names are different. So when
passing to a function/method that goes by only a set of index names, you'll
need to convert the index names before passing them to that function/method.
You don't need array_values To get your desired output you can just use
array_combine($new_index_names,$a1);
not in just 1 function, but you could use array_values to get the values of the first array, and array_combine to set the new keys
Assuming both arrays has equal count, one way is with array_combine() and array_values()
$a2 = array_combine(array_values($new_index_names), $a1);
The previous answers does not consider the order of $a1 and $new_index_names, so I put my solution following:
$a1 = array('one' => 1, 'two' => 2, 'three' => 3, 'zero' => 0);
$new_index_names = array('zero' => 'zero', 'one' => 'ono', 'two' => 'dos', 'three' => 'tres');
array_combine(
$new_index_names,
str_replace(array_keys($a1), array_values($a1), array_keys($new_index_names))
);
Array
(
[zero] => 0
[ono] => 1
[dos] => 2
[tres] => 3
)
The best answer I've seen thus far:
foreach ($a1 as $k => $v) $a2[$new_index_names[$k]] = $v;
Credits go to jh1711
Is there a way to encode variables as strings that can be evaluated as php code? In particular, I'm interested in associative arrays. (Scalar values and indexed arrays are encoded as valid php code by json_encode. I don't need to encode objects and resources).
$Array = ['1', 2, 'key' => 'value'];
php_encode($Array); // => "[0 => '1', 1 => 2, 'key' => 'value']" or similar
You can use var_export with the second parameter set to true:
function php_encode($val)
{
return var_export($val, true);
}
http://php.net/manual/en/function.var-export.php
I have several associative arrays in PHP that looks like this:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
....
I want to create another associative array, using the serialized values of the previous arrays are used as the array keys. For example:
$newArray = array("data1's serialized key" => "someNewValue", ... );
Are serialized arrays suitable for being used as array keys?
Do they contain any unacceptable characters?
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Are serialized arrays suitable for being used as array keys?
Yup! As far as I know you can use serialized arrays as a key in another array. But the I cannot think of any use-case for this. :P
Do they contain any unacceptable characters?
No, until and unless you specify any unacceptable characters in the original array.
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Nope.
So, you code would look like:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
$serializedArrayKey1 = serialize($data1);
$serializedArrayKey2 = serialize($data2);
$newArray = array($serializedArrayKey1 => "Value for data1", ...);
I'm new to JSON, but I have experience in PHP. Can someone explain to me how JSON works, especially with PHP, and EASY way would be nice.
EX: I have a php array like:
array(
array('id' => 1, 'img' => "http.img1.png", 'title' => 'ice cream'),
array('id' => 2, 'img' => "http.img2.png", 'title' => 'silly snail'),
array('id' => 3, 'img' => "http.img3.png", 'title' => 'big bear'),
array('id' => 4, 'img' => "http.img4.png", 'title' => 'Funny cat'),
);
is this fine, or should I alter this array? I want to convert this to a JSON Object. In the php array should there be a parent, and do I have to assign array elements as children, or can each php obj be it's own JSON obj? Thank you!
Just run json_encode on the variable that you want to turn into a json string.
$something = array("test" => array("value", "another value", 4));
echo json_encode($something)
This will produce
{"test":["value","another value",4]}
Also, putting that string into $something = json_decode("{"test":["value","another value",4]}"); will produce back the same array that was passed into json_encode.
Note that JSON is not a programming language; it is a way to represent objects. http://json.org has a complete visual representation of how to use it. JSON's main components are Arrays (surrounded by []) and Objects (surrounded by {}). Arrays are lists of comma separated values (see json.org for how to tell it the types...its pretty simple) while objects are key:value pairs separated by commas between each pair where they key is a string surrounded by quotation marks. Above I created an Object with a key called "test" whose value was an Array with two strings and a number in it.
Use json_encode() for encoding the array, get the array back by using json_decode().
Here's what I am trying to accomplish:
function foo($args) {
switch($args['type']) {
case 'bar':
bar($args['data']); // do something
break;
}
}
// or something like that
Which is basically a way of using named parameters in PHP.
Now, in order to build this $args array, I am forced to write ugly syntax like:
$builtArgs = array('type' => 'bar',
'data' => array(1, 2, 3),
'data2' => array(5, 10, 20)
);
foo($builtArgs);
Which gets uglier as I add more dimensions to the array, and also forces me to write tons of array(...) constructs. Is there a prettier way to do this?
For one thing, it could be done if we could use Python-like syntax:
$buildArgs = {'type' : 'bar', 'data' : [1, 2, 3], 'data2' : [5, 10, 20]};
But it is PHP.
You could create a JSON-encoded string and use json_decode() to convert it into a variable. This has syntax very similar to the Python-like syntax you mentioned.
$argstr = '{"type" : "bar", "data" : [1, 2, 3], "data2" : [5, 10, 20]}';
$buildArgs = json_decode($argstr, true);
EDIT: Updated code to accommodate #therefromhere's suggestion.
No. Alternative syntaxes for creating arrays have been proposed several times (the link lists 5 separate threads in the dev mailing list), but they were rejected.
No, there is no "short-syntax" to write arrays nor objects, in PHP : you have to write all those array().
(At least, there is no such syntax... yet ; might come in a future version of PHP ; who knows ^^ )
But note that have too many imbricated arrays like that will makes things harder for people who will have to call your functions : using real-parameters means auto-completion and type-hinting in the IDE...
There are no alternatives to constructing these nested arrays-- but there are options in how you can format your code that makes it readable. This is strictly preference:
return array
(
'text' => array
(
'name' => 'this is the second',
'this' => 'this is the third',
'newarr' => array
(
'example'
),
)
);
// Or using the long way
$array = array();
$array += array
(
'this' => 'is the first array'
);