9

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
marcin_koss
  • 5,763
  • 10
  • 46
  • 65
  • 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. – Brad Dec 11 '12 at 05:19
  • 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. – marcin_koss Dec 11 '12 at 05:22
  • 2
    Found your answer: http://stackoverflow.com/a/507195/362536 – Brad Dec 11 '12 at 05:25
  • 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... – Event_Horizon Dec 11 '12 at 05:28
  • Because, it is almost JSON format. – Roman Newaza Dec 11 '12 at 05:33
  • Brad, thanks for finding this! – marcin_koss Dec 11 '12 at 05:42
  • @Event_Horizon, I didn't assume... I asked. Yes, I read the question and looked at the tags. – Brad Dec 11 '12 at 15:56

1 Answers1

14

Check out the relatively new http_build_query function:

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)

dkamins
  • 21,450
  • 7
  • 55
  • 59