PHP join Function is an inbuilt function of PHP. It joins elements of an array into a single string. It returns a string containing elements of the array. In this article, we discuss the PHP join Function. Also, we will discuss a few examples demonstrating the usage of this function.
join( $delimiter , $array );
PHP join Function expects two parameters. One parameter is mandatory while the other is optional. However, it accepts the parameters in either order.
- $delimiter: Delimiter or the separator is an optional parameter and specifies by what character the array elements will be joined. The default value of delimiter is an empty string.
- $array: $array is an array of strings to join. It is a mandatory parameter.
The function returns a string from the elements of the array separated by the given delimiter.
Let us go through some of the examples to demonstrate the use of PHP join.
Example 1: Imploding with Newline Character
For example, let us join our array of strings with a ‘\n’ (newline character).
<?php $array = array('Hello!','What','a','beautiful','day','to','code.!'); $join = join("\n",$array); echo "<pre>"; print_r($join); echo "</pre>"; ?>
Output Hello! What a beautiful day to code.!
We can see from above example that our string got joined by newline character.
Example 2: No Value Passed To Function
For instance, let us see in this example that what happens if we do not pass any delimiter to the function.
<?php $array = array('Hello!','What','a','beautiful','day','to','code.!'); $join = join(" ",$array); echo "<pre>"; print_r($join); echo "</pre>"; ?>
Hello! What a beautiful day to code.!
By default, join function joins the array by ‘ ‘ (space), if we do not pass any delimiter to it.
You can read about more detailed examples on PHP implode Function.
In conclusion, we discussed PHP join Function. We also saw some of the examples showing it’s usage. Also, you can also check PHP’s official documentation for the join function. Moreover, you can read about PHP explode Function that works just the opposite of join function.
You can learn more about PHP Array Functions on Concatly!
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.