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?

7
  • 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. Commented Dec 11, 2012 at 5: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. Commented Dec 11, 2012 at 5:22
  • 2
    Found your answer: stackoverflow.com/a/507195/362536 Commented Dec 11, 2012 at 5: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... Commented Dec 11, 2012 at 5:28
  • Because, it is almost JSON format. Commented Dec 11, 2012 at 5:33

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately formatting is crucial here. Brad found solution to this. Thanks for help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.