Php format array to string

I have this php array:

$items = array (
    "Item 1" => "Value 1",
    "Item 2" => "Value 2",
    "Item 3" => "Value 3"
);

And I am wondering if there is an elegant PHP function I have never heard of to do the same as this:

$output = "";
foreach ( $items as $key => $value ) {
    $output .= sprintf( "%s: %s\n" , $key , $value );
}
echo $output;

Which of course, would output:

Item 1: Value 1
Item 2: Value 2
Item 3: Value 3

Also, what do you call that? Deserialization?

asked Jun 30, 2013 at 23:38

Andrew JackmanAndrew Jackman

13.4k7 gold badges34 silver badges44 bronze badges

13

There is always the array_walk function. Your example might look something like this:

function test_print($value, $key) {
    echo sprintf( "%s: %s\n" , $key , $value );
}

$items = array (
    "Item 1" => "Value 1",
    "Item 2" => "Value 2",
    "Item 3" => "Value 3"
);

array_walk($items, 'test_print');

After defining your function, you can then reuse array_walk($items, 'test_print'); as needed throughout your code.

There is also the array_walk_recursive function, if you're dealing with multidimensional arrays.

answered Jul 1, 2013 at 1:47

Php format array to string

1

There is nothing wrong with your solution except that you're missing a concatenation operator.

$output = "";
foreach ( $items as $key => $value ) {
    $output .= sprintf( "%s: %s\n" , $key , $value );
}
echo $output;

Bare in mind that this only handles single dimension arrays.

There are so many built-in functions in PHP that we sometimes forget that we actually have to write code. It was mentioned in the comments that you could use one of the array_* functions, such as array_reduce, but that will only lead to more complexity compared to your solution.

answered Jul 1, 2013 at 0:01

HerbertHerbert

5,5602 gold badges25 silver badges34 bronze badges

For more details, check details here

To convert an Array to String with PHP, we can use two different built-in functions available in PHP. These two functions only take one array at a time to convert it into a string.

  • Using json_encode() function
  • Using implode() function

Using json_encode() function to convert an Array to a string

To convert an array to a string, one of the common ways to do that is to use the json_encode() function which is used to returns the JSON representation of a value.

The syntax for using this function remains very basic-

json_encode ( mixed$value [, int $options = 0 [, int $depth = 512 ]] ) : string|false

This function takes any value as input except resource. But in our case, we’ll use an Array as an input value, and then this function will convert it into a JSON representation of the provided value.

<?php
$cars = array(
  array(
    'BMW' => 'Germany'
  ),
  array(
    'Ferrari' => 'Italy'
  ),
  array(
    'Honda' => 'Japan'
  )
);
echo json_encode($cars);

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

[{"BMW":"Germany"},{"Ferrari":"Italy"},{"Honda":"Japan"}]

At first glance, it doesn’t look like a string but this how JSON looks like. If we use var_dump() over json_encode() then it will show its data type as a string

var_dump(json_encode($cars));

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

string(57) "[{"BMW":"Germany"},{"Ferrari":"Italy"},{"Honda":"Japan"}]"

Using implode function to convert an array to a string

The syntax for implode function is quite simple-

implode ( string $glue , array $pieces ) : string

Here,

$glue: is the string / special character(s) used to concatenate array values. Default is an empty string.

$pieces: is the array whose values will stick together using glue.

This will return all the Array elements concatenated together using glue in the same sequential order in which they appear in the array.

1. Using Indexed Array

<?php
// using indexed array
$cars = array('BMW', 'Ferrari', 'Honda');
$cars_together = implode(", ", $cars);
echo $cars_together;

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

BMW, Ferrari, Honda

2. Using Associative array

<?php
$cars = array('BMW' => 'Germany', 'Ferrari' => 'Italy', 'Honda' => 'Japan');
$cars_together = implode(", ", $cars);
echo $cars_together;

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Germany, Italy, Japan

As mentioned above, all the values from the array will be stick together. Hence, if there is a situation where we need to get the values of the associative array to be glued together then use the same function.

3. Using Multidimensional Array

A multidimensional array can be simple OR complicated depending upon the situation in the project requirement. We will see the basic multidimensional array and for that, we need to write a callback function that will concatenate the values.

<?php
$automobile = array(
  array(
    'BMW' => 'Germany'
  ),
  array(
    'Ferrari' => 'Italy'
  ),
  array(
    'Honda' => 'Japan'
  )
);
echo implode(', ', array_map(function ($entry) {
  return ($entry[key($entry)]);
}, $automobile));

Enter fullscreen mode Exit fullscreen mode

// OUTPUT

Germany, Italy, Japan

Conclusion:

We can use any of the methods to fulfill the requirement. But when need to decide either to use json_encode() OR serialize(), I would always suggest using json_encode() because it takes smaller storage space as compared to serialize.

How do you make an array into a string?

Using StringBuffer.
Create an empty String Buffer object..
Traverse through the elements of the String array using loop..
In the loop, append each element of the array to the StringBuffer object using the append() method..
Finally convert the StringBuffer object to string using the toString() method..

How do you implode an array?

The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function. If we have an array of elements, we can use the implode() function to join them all to form one string.

How we can convert a multidimensional array to string without any loop in PHP?

function convert_multi_array($array) { foreach($array as $value) { if(count($value) > 1) { $array = implode("~", $value); } $array = implode("&", $value); } print_r($array); } $arr = array(array("blue", "red", "green"), array("one", "three", "twenty")); convert_multi_array($arr);

What is the name of function used to convert an array into a string?

PHP's implode function can be used to convert an array into a string --- it is similar to join in other languages. You can use it like so: $string_product = implode(',', $array);