How to implode array with key and value without foreach in PHP

php implode multidimensional array
implode array key php
php implode values of array
php implode associative array
array to string conversion in php without implode
php get array value by key
implode in php with comma
implode two array

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!).

and another way:

$input = array(
    'item1'  => 'object1',
    'item2'  => 'object2',
    'item-n' => 'object-n'
);

$output = implode(', ', array_map(
    function ($v, $k) {
        if(is_array($v)){
            return $k.'[]='.implode('&'.$k.'[]=', $v);
        }else{
            return $k.'='.$v;
        }
    }, 
    $input, 
    array_keys($input)
));

or:

$output = implode(', ', array_map(
    function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
    $input,
    array_keys($input)
));

implode - Manual, Without foreach, how can I turn an array like this array("item1"=>"object1", "item2"​=>"object2",."item-n"=>"object-n");. to a string like this By using our site, you acknowledge that you have read and understand our

You could use http_build_query, like this:

<?php
  $a=array("item1"=>"object1", "item2"=>"object2");
  echo http_build_query($a,'',', ');
?>

Output:

item1=object1, item2=object2 

Demo

PHP Implode Array Key Value - Array Keys To String, It's not obvious from the samples, if/how associative arrays are handled. The "​implode" function acts on the array "values", disregarding any keys: <?php declare(strict_types=1); foreach ($string_to_array as $value): echo "<li>"; echo $value; Home » Php » How to implode array with key and value without foreach in PHP How to implode array with key and value without foreach in PHP Posted by: admin November 13, 2017 Leave a comment

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):

$array = [
    'test0' => 344,
    'test1' => 235,
    'test2' => 876,
    ...
];

Test number one:

Use http_build_query and str_replace:

str_replace('=', ':', http_build_query($array, null, ','));

Average time to implode 1000 elements: 0.00012930955084904

Test number two:

Use array_map and implode:

implode(',', array_map(
        function ($v, $k) {
            return $k.':'.$v;
        },
        $array,
        array_keys($array)
    ));

Average time to implode 1000 elements: 0.0004890081976675

Test number three:

Use array_walk and implode:

array_walk($array,
        function (&$v, $k) {
            $v = $k.':'.$v;
        }
    );
implode(',', $array);

Average time to implode 1000 elements: 0.0003874126245348

Test number four:

Use foreach:

    $str = '';
    foreach($array as $key=>$item) {
        $str .= $key.':'.$item.',';
    }
    rtrim($str, ',');

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

How to implode array with key and value without foreach (PHP , The method I use will convert array key values into an array without using foreach​() function. The idea of this code snippet will allow you to  Luckily in PHP there is a function called array_keys() which will return a list of array keys from the array. Combining these two functions, we can easily convert the keys of an array into a string. Using php implode array key value will easily convert your array’s keys into a string. Note that as this function converts the array keys into a string rather than the array values.

I would use serialize() or json_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.

PHP array_keys() Function, and another way: $input = array( 'item1' => 'object1', 'item2' => 'object2', 'item-n' =​> 'object-n' ); $output = implode(', ', array_map( function ($v,  The implode function of PHP is used to convert an array into a string. The resultant string may be joined with a specified character like comma, + sign etc. implode with simple array example With associative array Syntax of using the PHP implode method. Following is the general syntax for using the implode method:

Using array_walk

$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");
$r=array();
array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));
echo implode(', ', $r);

IDEONE

PHP implode for converting arrays to string with 6 examples, Not depending on type, the number 5 is the same as the string "5". Technical Details. Return Value: Returns an array containing the keys. PHP Version  You've got a very good point regarding your second comment, but in this case singles solution will do just fine. And yes, i am a bit skeptical about creating functions for this kind of usage.

PHP "Array to String" (Examples of How to Use the implode Function , The implode function of PHP is used to convert an array to string. The return value after using the implode PHP function is a string, so you may assign it to a string variable. This order will also produce the same result without any error: PHP switch case statement · PHP foreach · PHP explode / Split string · PHP isset​  The function here flatterns an entire array and was not the behaviour I expected from a function of this name. I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.

How To Get The First Element Of An Array In PHP?, In PHP, the implode() method joins array elements and outputs them as a single string. This is useful when you need to create one string out of a set of array values. The function can be invoked in two ways (with or without the glue string): Along with key review factors, this compensation may impact how  The array of strings to implode. Return Values Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

How to create comma separated list from an array in PHP , However, starting from PHP 7.1, you can specify the specific key you're looking access the value of the first element of an out-of-order or non-sequential array. We can simply make use of the foreach loop to go one round and The PHP reset() function not only resets the internal pointer of the array to  Rückgabewerte. Gibt einen String mit einer String-Repräsentation aller Array-Elemente in der gleichen Reihenfolge wie in dem Array zurück, bei dem die einzelnen Array-Elemente mit dem im Parameter glue angegebenen String verbunden werden.

Comments
  • How nested foreach would be necesarry?
  • What are you attempting? Why do you have those constraints?
  • this was my database class for web app i'm building, i don't want it to look messy since it's already populated with a bunch of foreach and for-loop all together
  • This selected answer is method that you asked for, however it should be noted that it is critically slower and that if you are storing this information via a database it would be vastly superior to both a loop and this to just use json_encode. Exhibit A: willem.stuursma.name/2010/11/22/…
  • possible duplicate of Fastest way to implode an associative array with keys
  • This method is what the Author was asking for, but it should be noted that it is critically slower and that if you are storing this information via a database it would be vastly superior to both a loop and this to just use json_encode. Exhibit A: willem.stuursma.name/2010/11/22/…
  • None of the links here seem to work anymore, they all echo "Hello, World!"; Should I be seeing code examples of those functions?
  • This method is very easy to customize according to own demand.
  • Never used the other parameters of http_build_query.
  • +1 Hell yeah I love finding little nuggets of goodness like this :)