PHP 101
  • Home
  • Deploy
  • How-to
  • Tutorial
No Result
View All Result
PHP 101
  • Home
  • Deploy
  • How-to
  • Tutorial
No Result
View All Result
PHP 101
No Result
View All Result
Home How-to

How to convert from array to string in PHP

Short guide on converting from array to string using PHP easily that works.

March 9, 2022
Reading Time: 4 mins read
PHP101.net - How to convert array to string in PHP

PHP101.net - How to convert array to string in PHP

Share on FacebookShare on Twitter

Suppose that you have an PHP array of fruits, and you want to convert it into a comma-separated list like this:

// Source array
$fruits = ['Orange', 'Apple', 'Banana']

// Expected result: Orange, Apple, Banana

This article will guide you on how to achieve that: Convert from array to string in PHP.

There are plenty of methods to do so, which we will provide all of them, from traditional for, foreach to using implode functions, and we will give our opinions on the advantages and disadvantages of each method.

Why so many methods? Isn’t implode already good?

We always try to be creative and flexible in PHP development, so it will pay off in case of large-scale projects which doesn’t always good to write code using one method.

3 methods to convert array to string in PHP

We will use the given fruits array as mentioned in the intro:

$fruits = ['Orange', 'Apple', 'Banana'];

1. Using for() loop

This is the traditional method to convert array to string using PHP. We will:

  • Loop through the array elements
  • Extract the text from each element and push it to the $output
  • Add the comma (,) if it is not the last element (to prevent obsolete comma at the end)
// Prepare the output text
$output = '';

// Loop through the array and extract the text
for ( $i = 0; $i < count( $fruits ); $i++ ) {

    // Add the string to text output
    $output .= $fruits[$i];

    // Add the comma (and a space) ONLY if this element is not the last one
    // Why minus 1? Because array index starts from 0 so the correct last element index MUST minus 1
    if ( $i != count( $fruits ) - 1 ) {
        $output .= ', ';
    }
}

We will get the result as expected:

Orange, Apple, Banana

*Quick tips: The conditional check for last element can be used with the array_key_last function, which will return the last element’s key in the array. However, this function only work with PHP 7.3.0+. Example:

if ( $i != array_key_last( $fruits ) ) {
    $output .= ', ';
}

See PHP.net Official Documentation on array_key_last.

Pros of using for loop

  • The iteration is clearly defined (by the $i variable)
  • Break (stop) conditional is easier to specify

Cons of using foreach loop

  • Worse performance than foreach loop
  • Cannot be used with string-based element keys
  • count() function has to be used properly

2. Using foreach() loop

Another array looping method to convert array to string using PHP is foreach loop. It’s mostly similar with for loop, just a little different with the syntax:

// Prepare output
$output = '';

// Loop through the array using foreach
foreach ( $fruits as $key => $fruit ) {
   
    // Add the string to text output
    $output .= $fruit;

    // Check if the element is the last one by using array_key_last
    if ( $key != array_key_last( $fruits ) ) {
        $output .= ', ';
    }
}

Again, this will provide us with the similar result.

Pros of using foreach loop

  • Better performance than for loop
  • Can be used with string-based element keys

Cons of using foreach loop

  • The iteration is not clearly defined (had to declare $key => $value)
  • Break (stop) condition has to be clearly defined

3. Using implode() function

Finally, the simplest method to convert array to string in PHP is the implode function. It will simply join the elements in the array into a text string, using the first parameter as the separator.

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

In our example, this is how we use implode to achieve the result:

// Join the array elements into one string using comma + space as separator
$output = implode( ', ' , $fruits )

This will instantly show the result as expected.

Pros of using implode function

  • Easy to implement
  • Can avoid the last obsolete separator compared to looping methods

Cons of using implode function

  • Looping can work better with element conditional check

What to use?

If you simply want to join the array elements into one string, use implode.

If not only joining but extra conditional check is required, like excluding elements by specific criteria, using for and foreach is recommended.

Final thoughts

That’s all for this how-to guide on the methods to convert from array to string using PHP. Hopefully this guide could help you with your PHP development. We always constantly update and release new helpful PHP tutorials.

Thanks for reading!

You might also like

  • How to download file from URL using PHP
  • How to write PHP comments (and best practices)

References

  • PHP.net Official Documentation on implode function
  • PHP.net Official Documentation on for loop
  • PHP.net Official Documentation on foreach loop
Tags: array to stringarray to string in phparray to string using phpphp array to string
Previous Post

How to download file from URL using PHP

Next Post

How to set MySQL charset (or MariaDB) by PHP

Related Posts

PHP101.net - How to set timezone with PHP

How to set timezone with PHP easily (multiple methods)

March 9, 2023
PHP101.net - How to redirect to another page using PHP

How to redirect to another page using PHP

March 8, 2023

Table of Contents

    • Why so many methods? Isn’t implode already good?
    • 3 methods to convert array to string in PHP
    • 1. Using for() loop
    • 2. Using foreach() loop
    • 3. Using implode() function
    • What to use?
    • Final thoughts
    • You might also like
Next Post
PHP101.net - How to set MySQL charset by PHP

How to set MySQL charset (or MariaDB) by PHP

We deliver free and helpful resources for learning
and using PHP programming language.

About
Contact Us
Privacy Policy
Main Sections

Home
Deploy
How-to
Tutorial
You might be interested in...

How to get user IP address using PHP

How to set MySQL charset (or MariaDB) by PHP

How to install ImageMagick on Windows

How to copy files using PHP

Deploy a webserver with Laragon on Windows for PHP development

© 2022 PHP101.Net - Helpful PHP Tutorials, How-to, Tips and Tricks for everyone.

No Result
View All Result
  • Home
  • Deploy
  • How-to
  • Tutorial

© 2022 PHP101.Net - Helpful PHP Tutorials, How-to, Tips and Tricks for everyone. | Privacy Policy

This website uses cookies. By continuing to use this website you are giving consent to cookies being used. Visit our Privacy and Cookie Policy.