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:


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

      • 2
    • Does the output format matter? json_encode() is really handy for something structured, and very similar to what you are looking for. And then, you don't have to worry about escaping and what not, as it does it for you.
      • 1
    • Yes, output format matters. I want the generate a part of SQL query. I know PHP 5.3 doesn't have list comprehension but I was thinking maybe some set of functions will do the job. Thanks Brad.
    • I find it funny that 2 people assumed JSON encode/decode would help with this, did anyone look at the tags or read the actual question? Its an associative array to string conversion, and hes using Python AA to get a string...

Check out the relatively new http_build_query function:


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


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)

  • 14
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions