PHP - How to convert array to string

  • Last update: Apr 3, 2024
  • Views: 24
  • Author: Admin
PHP - How to convert array to string

Hello colleagues.

Sooner or later, every web developer in his projects is faced with such a task as to collect a string from an array in the PHP programming language. One such example of why you might need to collect a string from an array is when you received data about the user's date of birth in the form of an array from a form, and you need to collect a string from this array and add this string to one of your database fields.

In this article, we will talk about some simple built-in php functions that will help you collect a string from an array without any difficulties.

 

Article content:

  1. PHP function implode.
  2. PHP join function.
  3. Results.

 

1. PHP implode function.

The first function we'll talk about is called implode. The implode function takes two required parameters, the first parameter is the connector, the default parameter value is an empty string, and the second parameter is the array itself. The function, as you already understood, returns a string in cases of success, otherwise exceptions will be thrown.

Function syntax.

implode(string $separator, array $array): string

Example.

<?php
$array = [
    '12',
    '01',
    '1993'
];
$text = implode(",", $array);
?>

php array to string

As you can see from the example, we have an array of three elements, and I wanted a string to be obtained from this array and there was a comma between the values ​​of each of the array elements.


 

2. PHP join function.

The second function that will help us collect a string from an array is called join. The join function is the same in its functionality as the implode function.

Function syntax.

join(string $separator, array $array): string

Example.

<?php
$array = [
    '12',
    '01',
    '1993'
];
$text = join(",", $array);
?>

php array to string

As a result, we get the same string as when using the implode function.


 

3. Results.

As a result of a colleague, today we have successfully met so that a string can be assembled from an array without any problems. The functions that we analyzed today are exactly the same in their functionality, and you can use the one that you like the most.


 

Thank you all, I hope my article was of some help to you.

SIMILAR ARTICLES