Join all elements of an array together and become a string
There are many elements in an array. In some operations, you might like to join all the elements within an array to become a string and use the string for other operation, how can this be done?? There is a function of PHP can do the job, which is implode( ). Let me show how to do so:
First the implode( ) function take in 2 parameters:
- The separator string between each elements, I use S to represent it.
- The array. I use A to represent it.
So with the 2 parameters we get for implode( ):
implode(“S“, A);
The separator string S must be within a pair of ” .
Here is an example:
First, we create an array:
1 2 3 4 5 6 7 | <?php $arrayOne[0] = "Hi"; $arrayOne[1] = "how"; $arrayOne[2] = "are"; $arrayOne[3] = "you"; $arrayOne[4] = "today"; ?> |
Now we use implode( ) to join them all together into a string and with a space between them. We create a PHP variable: $astring to store the new string.
1 2 3 4 5 6 7 8 9 | <?php $arrayOne[0] = "Hi"; $arrayOne[1] = "how"; $arrayOne[2] = "are"; $arrayOne[3] = "you"; $arrayOne[4] = "today"; $astring = implode(" ", $arrayOne ); ?> |
At last, we print out the string and see if everything goes correctly:
1 2 3 4 5 6 7 8 9 10 11 | <?php $arrayOne[0] = "Hi"; $arrayOne[1] = "how"; $arrayOne[2] = "are"; $arrayOne[3] = "you"; $arrayOne[4] = "today"; $astring = implode(" ", $arrayOne ); echo $astring; ?> |
This should give us an output:
Hi how are you today





Add A Comment