PHP join Function | Join Array Elements into a String

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 is an alias of PHP implode Function. Also, you can learn about PHP explode Function that works just the opposite of the join function.

Syntax

join( $delimiter ,  $array );

Parameters

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.

Return Value

The function returns a string from the elements of the array separated by the given delimiter.

PHP join function | join elements of array to string

Examples

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.

Conclusion

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!

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *