PHP Array to String Conversion
Sometimes data arrive in array which has to be convert into string, in this situation we can use implode() function which is used to convert the array into string.
In PHP, conversion of an array to string is done by implode() function. The implode() function puts the separator (In general we use: + , or any other special symbol) between each value of the array. This function joins array elements with a string.
General format of the implode() function is:
- string implode ($separator, $array)
- string implode ($array)
- string implode ($array, $separator)
One important point about implode function is that it accepts its parameter in either order, if you don't pass any separator, even any space, PHP wont generate any warning or error message.
PHP Array to String Conversion Example 1:
<?php $array1=$array2=array("CPU","VDU","KEYBOARD"); $array1=implode($array1,","); print_r($array1); echo"<br/>"; $array1=implode("+",$array2); print_r($array1); ?>
Output:
CPU,VDU,KEYBOARD CPU+VDU+KEYBOARD
join() function is an alias for implode(), output will be same as implode() function, example of join() is as follows:
Convert Array to String in PHP Example 2:
<?php $array1=$array2=array("CPU","VDU","KEYBOARD"); $array1=join($array1,","); print_r($array1); echo"<br/>"; $array1=join("+",$array2); print_r($array1); ?>
Output:
CPU,VDU,KEYBOARD CPU+VDU+KEYBOARD