The server-side scripting language for web, PHP supports the array data type which has very interesting use cases to store data in the program. As a web developer it is important to know the various operations on array data type to code highly efficient web scripts. PHP provides with lots of in-built methods to perform operations on array.
In this code, we have a favouriteColors array which contains the string elements. Then we declare a string variable and in this store the result of join operation performed on array, favouriteColors. It will output in the order of elements, , separated values.
Favourite Colors are: Red, Yellow, Blue
This is easy with PHP's inbuilt function but we can also write a code to create a string from array.
Code
<?php
$string = ''; //Empty string initally.
foreach ($array as $key => $value) {
$string .= ",$value"; //Add into string value
}
$string = substr($string, 1); //To remove the first , from first element
?>
It works same as the join function. We iterate the array using a loop and in the string variable store the string that joins the element preceded by , symbol. Finally, we remove the first , using the substr() method that will return the string from index 1 to string length, i.e, discard the first , in the string.
This is how we join the elements of an array into a string in PHP? Share your thoughts in the comments below.
Here's an example which uses this PHP method effectively,
In this code, we have a favouriteColors array which contains the string elements. Then we declare a string variable and in this store the result of join operation performed on array, favouriteColors. It will output in the order of elements, , separated values.
This is easy with PHP's inbuilt function but we can also write a code to create a string from array.
Code
It works same as the join function. We iterate the array using a loop and in the string variable store the string that joins the element preceded by , symbol. Finally, we remove the first , using the substr() method that will return the string from index 1 to string length, i.e, discard the first , in the string.
This is how we join the elements of an array into a string in PHP? Share your thoughts in the comments below.
need an explanation for this answer? contact us directly to get an explanation for this answer