Convert array to string php w3schools

❮ PHP String Reference

Example

Join array elements with a string:

$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>

Try it Yourself »


Definition and Usage

The implode() function returns a string from the elements of an array.

Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments.

Note: The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility.

Note: This function is binary-safe.


Syntax

Parameter Values

ParameterDescription
separator Optional. Specifies what to put between the array elements. Default is "" (an empty string)
array Required. The array to join to a string

Technical Details

Return Value:Returns a string from elements of an array
PHP Version:4+
Changelog:The separator parameter became optional in PHP 4.3.0

More Examples

Example

Separate the array elements with different characters:

$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr)."
";
echo implode("+",$arr)."
";
echo implode("-",$arr)."
";
echo implode("X",$arr);
?>

Try it Yourself »


❮ PHP String Reference


❮ PHP String Reference

Example

Break a string into an array:

$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>

Try it Yourself »


Definition and Usage

The explode() function breaks a string into an array.

Note: The "separator" parameter cannot be an empty string.

Note: This function is binary-safe.


Syntax

explode(separator,string,limit)

Parameter Values

ParameterDescription
separator Required. Specifies where to break the string
string Required. The string to split
limit Optional. Specifies the number of array elements to return.

Possible values:

  • Greater than 0 - Returns an array with a maximum of limit element(s)
  • Less than 0 - Returns an array except for the last -limit elements()
  • 0 - Returns an array with one element


Technical Details

Return Value:Returns an array of strings
PHP Version:4+
Changelog:The limit parameter was added in PHP 4.0.1, and support for negative limits were added in PHP 5.1.0

More Examples

Example

Using the limit parameter to return a number of array elements:

$str = 'one,two,three,four';

// zero limit
print_r(explode(',',$str,0));

// positive limit
print_r(explode(',',$str,2));

// negative limit
print_r(explode(',',$str,-1));
?>

Try it Yourself »


❮ PHP String Reference


(PHP 4, PHP 5, PHP 7, PHP 8)

implodeJoin array elements with a string

Description

implode(string $separator, array $array): string

Alternative signature (not supported with named arguments):

implode(array $array): string

Legacy signature (deprecated as of PHP 7.4.0, removed as of PHP 8.0.0):

implode(array $array, string $separator): string

Parameters

separator

Optional. Defaults to an empty string.

array

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 separator string between each element.

Changelog

VersionDescription
8.0.0 Passing the separator after the array is no longer supported.
7.4.0 Passing the separator after the array (i.e. using the legacy signature) has been deprecated.

Examples

Example #1 implode() example

$array

= ['lastname''email''phone'];
var_dump(implode(","$array)); // string(20) "lastname,email,phone"

// Empty string when using an empty array:

var_dump(implode('hello', [])); // string(0) ""

// The separator is optional:

var_dump(implode(['a''b''c'])); // string(3) "abc"?>

Notes

Note: This function is binary-safe.

See Also

  • explode() - Split a string by a string
  • preg_split() - Split string by a regular expression
  • http_build_query() - Generate URL-encoded query string

houston_roadrunner at yahoo dot com

13 years ago

it should be noted that an array with one or no elements works fine. for example:

    $a1 = array("1","2","3");
   
$a2 = array("a");
   
$a3 = array();

        echo

"a1 is: '".implode("','",$a1)."'
"
;
    echo
"a2 is: '".implode("','",$a2)."'
"
;
    echo
"a3 is: '".implode("','",$a3)."'
"
;
?>

will produce:
===========
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''

biziclop

1 year ago

Sometimes it's necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.

function wrap_implode( $array, $before = '', $after = '', $separator = '' ){
  if( !
$array )  return '';
  return
$before . implode("{$after}{$separator}{$before}", $array ) . $after;
}

echo

wrap_implode(['path','to','file.php'], '/');
// "/path/to/file.php"$pattern = '#'. wrap_implode([4,2,2], '\d{', '}', '[-.]') .'#';
echo
$pattern, "\n"// #\d{4}[-.]\d{2}[-.]\d{2}#
echo preg_replace( $pattern, '[REDACTED]', 'The UFO appeared between 2012-12-24 and 2013.01.06 every night.');
// 'The UFO appeared between [REDACTED] and [REDACTED] every night.echo wrap_implode(['line','by','line'], '', '', '
  '
);
// line
  by
  line
echo wrap_implode( ['Menu Item 1', 'Menu Item 2',],
 
"
  • ", "
  • \n"
    ,
     
    "
  • |
  • \n"
    ,
    );
    /*
  • Link1

  • |

  • Link2

  • */
    ?>

    ASchmidt at Anamera dot net

    3 years ago

    It's not obvious from the samples, if/how associative arrays are handled. The "implode" function acts on the array "values", disregarding any keys:

    declare(strict_types=1);$a = array( 'one','two','three' );
    $b = array( '1st' => 'four', 'five', '3rd' => 'six' );

    echo

    implode( ',', $a ),'/', implode( ',', $b );
    ?>

    outputs:
    one,two,three/four,five,six

    omar dot ajoue at kekanto dot com

    9 years ago

    Can also be used for building tags or complex lists, like the following:

    $elements

    = array('a', 'b', 'c');

    echo

    "
    • " . implode("
    • ", $elements) . "
    "
    ;?>

    This is just an example, you can create a lot more just finding the right glue! ;)

    Honk der Hase

    2 years ago

    If you want to implode an array as key-value pairs, this method comes in handy.
    The third parameter is the symbol to be used between key and value.

    function mapped_implode($glue, $array, $symbol = '=') {
        return
    implode($glue, array_map(
                function(
    $k, $v) use($symbol) {
                    return
    $k . $symbol . $v;
                },
               
    array_keys($array),
               
    array_values($array)
                )
            );
    }
    $arr = [
       
    'x'=> 5,
       
    'y'=> 7,
       
    'z'=> 99,
       
    'hello' => 'World',
       
    7 => 'Foo',
    ];

    echo

    mapped_implode(', ', $arr, ' is ');// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo?>

    Felix Rauch

    6 years ago

    It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.

    Example:
    class Foo
    {
        protected
    $title;

        public function

    __construct($title)
        {
           
    $this->title = $title;
        }

        public function

    __toString()
        {
            return
    $this->title;
        }
    }
    $array = [
        new
    Foo('foo'),
        new
    Foo('bar'),
        new
    Foo('qux')
    ];

    echo

    implode('; ', $array);
    ?>

    will output:

    foo; bar; qux

    alexey dot klimko at gmail dot com

    11 years ago

    If you want to implode an array of booleans, you will get a strange result:
    var_dump(implode('',array(true, true, false, false, true)));
    ?>

    Output:
    string(3) "111"

    TRUE became "1", FALSE became nothing.

    Anonymous

    9 years ago

    It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:
    var_dump(implode(':', 'xxxxx'));
    ?>
    returns
    NULL

    This threw me for a little while.

    masterandujar

    10 years ago

    Even handier if you use the following:

    $id_nums = array(1,6,12,18,24); $id_nums = implode(", ", $id_nums); $sqlquery = "Select name,email,phone from usertable where user_id IN ($id_nums)"; // $sqlquery becomes "Select name,email,phone from usertable where user_id IN (1,6,12,18,24)"
    ?>

    Be sure to escape/sanitize/use prepared statements if you get the ids from users.

    Anonymous

    7 years ago

    null values are imploded too. You can use array_filter() to sort out null values.

    $ar = array("hello", null, "world");
    print(
    implode(',', $ar)); // hello,,world
    print(implode(',', array_filter($ar, function($v){ return $v !== null; }))); // hello,world
    ?>

    Rafael Pereira

    2 years ago

    If you want to use a key inside array:

    Example:
    $arr=array(
    array("id" => 1,"name" => "Test1"),
    array("id" => 2,"name" => "Test2"),
    );

    echo implode_key(",",$arr, "name");
    OUTPUT: Test1, Test2

    function implode_key($glue, $arr, $key){
        $arr2=array();
        foreach($arr as $f){
            if(!isset($f[$key])) continue;
            $arr2[]=$f[$key];
        }
        return implode($glue, $arr2);
    }

    admin at lanlink dot net dot au

    5 years ago

    It is possible for an array to have numeric values, as well as string values. Implode will convert all numeric array elements to strings.

    $test=implode(["one",2,3,"four",5.67]);
    echo
    $test;
    //outputs: "one23four5.67"
    ?>

    info at ensostudio dot ru

    2 years ago

    * Join pieces with a string recursively.
    *
    * @
    param mixed $glue String between pairs(glue) or an array pair's glue and key/value glue or $pieces.
    * @param iterable $pieces Pieces to implode (optional).
    * @return string Joined string
    */
    function double_implode($glue, iterable $pieces = null): string
    {
        $glue2 = null;
        if ($pieces === null) {
            $pieces = $glue;
            $glue = '';
        } elseif (is_array($glue)) {
            list($glue, $glue2) = $glue;
        }

            $result = [];
        foreach ($pieces as $key => $value) {
            $result[] = $glue2 === null ? $value : $key . $glue2 . $value;
        }
        return implode($glue, $result);
    }
    ?>
    Examples:
    $array = ['

    a' => 1, 'b' => 2];
    $str =  implode($array);
    $str =  implode('
    , ', $array);
    $str =  implode(['" ', '="'], $array);

    $iterator = new ArrayIterator($array);
    $str =  implode($iterator);
    $str =  implode('

    , ', $iterator);
    $str =  implode(['" ', '="'], $iterator);
    ?>

    info AT sinistercircuits DOT com

    10 months ago

    There is no mention of behavior on a empty array, so I tried it and here's the result:

    $ar = array();
    $result = implode(',', $ar);  // Comma arbitrarily applied as the separator
    $is_result_empty = empty($result);
    ?>

    $result:
    $is_result_empty: 1

    In other words, an empty string is the result.

    How do I turn an array into a string in PHP?

    There are two ways to convert an array into a string in PHP..
    Using implode() function..
    Using json_encode() function..

    What is implode () in PHP?

    The implode() function in PHP is called “array to a string,” as it takes an array of elements and returns a string. For example, if we want to join an array of elements to form one string, we can use the implode() function to perform the same.

    What are the uses of explode () and implode () functions?

    While explode() function is used to output an array by breaking apart a string with the help of another string, the implode() function is used to output a string by joining the elements(strings) of an array with the help of another string.

    What is Str_split function in PHP?

    The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.