Without foreach, how can I turn an array like this
array("item1"=>"object1", "item2"=>"object2",......."item-n"=>"object-n");
to a string like this
item1='object1', item2='object2',.... item-n='object-n'
I thought about implode()
already, but it doesn't implode the key with it.
If foreach it necessary, is it possible to not nest the foreach?
EDIT: I've changed the string
EDIT2/UPDATE: This question was asked quite a while ago. At that time, I wanted to write everything in one line so I would use ternary operators and nest built in function calls in favor of foreach. That was not a good practice! Write code that is readable, whether it is concise or not doesn't matter that much.
In this case: putting the foreach in a function will be much more readable and modular than writing a one-liner(Even though all the answers are great!).
I spent measurements (100000 iterations), what fastest way to glue an associative array?
Objective: To obtain a line of 1,000 items, in this format: "key:value,key2:value2"
We have array (for example):
Test number one:
Use http_build_query and str_replace:
Average time to implode 1000 elements: 0.00012930955084904
Test number two:
Use array_map and implode:
Average time to implode 1000 elements: 0.0004890081976675
Test number three:
Use array_walk and implode:
Average time to implode 1000 elements: 0.0003874126245348
Test number four:
Use foreach:
Average time to implode 1000 elements: 0.00026632803902445
I can conclude that the best way to glue the array - use http_build_query and str_replace
Using array_walk
IDEONE
I would use
serialize()
orjson_encode()
.While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.
and another way:
or:
You could use http_build_query, like this:
Output:
Demo
Change
if you want to resive the entire String without the last $glue
And the usage: