Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting associative array into string of "id = value, id = value" in one line in PHP

In Python I would do something like this heaving the following dictionary (equiv of php's assoc array).

arr = {'id': '1', 'name': 'marcin', 'born': '1981-10-23'}
print ', '.join([('`%s` = "%s"') % (k,v) for k,v in arr.items()])

to get:

`born` = "1981-10-23", `id` = "1", `name` = "marcin"

Assuming PHP array is:

array("id"=>"1","name"=>"marcin","born"=>"1981-10-23");

Is there a way of getting the same result in PHP 5.3 without using foreach loop?

like image 239
marcin_koss Avatar asked Dec 11 '12 05:12

marcin_koss


People also ask

How do you convert associative array to string?

To convert an array to a string, one of the common ways to do that is to use the json_encode() function which is used to returns the JSON representation of a value. This function takes any value as input except resource.

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

How we can convert a multidimensional array to string without any loop?

Maybe in case you need to convert a multidimensional array into a string, you may want to use the print_r() function. This is also called “array with keys”. By adding “true” as its second parameter, all the contents of the array will be cast into the string.

Which associative array is used to pass data to PHP?

The $_POST is an associative array of variables. These variables can be passed by using a web form using the post method or it can be an application that sends data by HTTP-Content type in the request.


1 Answers

Check out the relatively new http_build_query function:

  • http://php.net/manual/en/function.http-build-query.php

E.g.

echo http_build_query(array('foo'=>'bar', 'zig'=>'zag', 'tic'=>'tac'), '', ', ');

outputs:

foo=bar, zig=zag, tic=tac

It's intended for making query strings, but the 3rd argument arg_separator can be any string (default "&").

(This doesn't address your quoting concerns, but it may still be helpful)

like image 174
dkamins Avatar answered Oct 15 '22 21:10

dkamins