Open In App

How to Convert Array to String in PHP?

Last Updated : 16 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We are given an array and the task is to convert the array elements into a string.

Below are the approaches to convert an array to a string in PHP:

Using implode() function

The implode() method is an inbuilt function in PHP and is used to join the elements of an array. The implode() method is an alias for PHP | join() function and works exactly the same as that of the join() function.

Syntax:

string implode($separator, $array)

Example:

PHP
<?php  

// Declare an array 
$arr = array("Welcome","to", "GeeksforGeeks", 
    "A", "Computer","Science","Portal");  
  
// Converting array elements into
// strings using implode function
echo implode(" ",$arr);
 
?>

Output:

Welcome to GeeksforGeeks A Computer Science Portal

Using json_encode() Function

The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation.

Syntax:

string json_encode( $value, $option, $depth )

Example:

PHP
<?php 

// Declare multi-dimensional array 
$value = array( 
    "name"=>"GFG", 
    array( 
        "email"=>"abc@gfg.com", 
        "mobile"=>"XXXXXXXXXX"
    ) 
); 

// Use json_encode() function 
$json = json_encode($value); 

// Display the output 
echo($json); 

?> 

Output:

{"name":"GFG","0":{"email":"abc@gfg.com","mobile":"XXXXXXXXXX"}}

Using sprintf

This PHP code uses sprintf() to format an array into a string. The %s placeholders in the format string match each array element, expanding with …$array, resulting in “Hello World in PHP” as output.

Example:

PHP
<?php
$array = array('Hello', 'World', 'in', 'PHP');
$string = sprintf('%s %s %s %s', ...$array);

echo $string;  // Output: Hello World in PHP
?>

Output
Hello World in PHP

Using serialize() Function

The serialize() function creates a serialized string representation of a PHP value, including arrays. This can be useful for storing arrays in a text format that can be easily restored.

Example: In this example, the convertArrayToString function uses the serialize() function to convert the input array into a serialized string. This string can be stored or transmitted as needed.

PHP
<?php
function convertArrayToString($array) {
    return serialize($array);
}

// Example usage
$array = ['name' => 'GFG', 'email' => 'abc@gfg.com', 'mobile' => 'XXXXXXXXXX'];
$string = convertArrayToString($array);
echo $string;
// Output: a:3:{s:4:"name";s:3:"GFG";s:5:"email";s:12:"abc@gfg.com";s:6:"mobile";s:10:"XXXXXXXXXX";}

// To unserialize back to array
$unserializedArray = unserialize($string);
print_r($unserializedArray);


?>

Output
a:3:{s:4:"name";s:3:"GFG";s:5:"email";s:11:"abc@gfg.com";s:6:"mobile";s:10:"XXXXXXXXXX";}Array
(
    [name] => GFG
    [email] => abc@gfg.com
    [mobile] => XXXXXXXXXX
)

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Similar Reads

How to Convert Integer array to String array using PHP?
Given is an integer Array, the task is to convert the Integer array to a String array and print the output. Example: Input: $integerArray = [10, 20, 30, 40, 50];Output: ["10", "20", "30", "40", "50"]These are the following approaches: Table of Content Using the array_map() and strval() functionUsing a loop and String castingUsing a loop and strval(
4 min read
Convert a String into an Array of Characters in PHP
Given a string, the task is to convert the string into an array of characters using PHP. Examples: Input: str = "GFG" Output: Array( [0] => G [1] => f [2] => G)Input: str = "Hello Geeks"Output: Array( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => G [7] => e [8] => e [9] => k [10] => s)There are
4 min read
How to Convert Byte Array to String in PHP?
Given a Byte Array, the task is to convert the byte array to a String in PHP. It is used in various scenarios, such as processing binary data, handling file uploads, or working with data transmission protocols. Below are the approaches to convert byte array to string in PHP: Table of Content What is a Byte Array?Using implode() FunctionUsing pack()
3 min read
PHP Program to Convert Array to Query String
This article will show you how to convert an array to a query string in PHP. The Query String is the part of the URL that starts after the question mark(?). Example: Input: $arr = ( 'company' => 'GeeksforGeeks', 'Address' => 'Noida', 'Phone' => '9876543210');Output: company=GeeksforGeeks&Address=Noida&Phone=9876543210There are two
3 min read
How to Convert Query String to an Array in PHP?
In this article, we will see how to convert a query string to an array in PHP. The Query String is the part of the URL that starts after the question mark(?). Examples: Input: str = "company=GeeksforGeeks&amp;address=Noida&amp;mobile=9876543210"Output: Array ( [company] => GeeksforGeeks [address] => noida [mobile] => 9876543210)Inp
4 min read
How to convert string to boolean in PHP?
Given a string and the task is to convert given string to its boolean. Use filter_var() function to convert string to boolean value. Examples: Input : $boolStrVar1 = filter_var('true', FILTER_VALIDATE_BOOLEAN); Output : true Input : $boolStrVar5 = filter_var('false', FILTER_VALIDATE_BOOLEAN); Output : false Approach using PHP filter_var() Function:
2 min read
How to convert a String to Lowercase in PHP?
Converting a string to lowercase in PHP is a common operation that allows you to standardize string formats or perform case-insensitive comparisons. Table of Content Using strtolower() functionUsing mb_strtolower() functionUsing str_replace( ) functionUsing LoopUsing strtolower() function:PHP strtolower() converts all alphabetic characters in a str
1 min read
PHP Program to Convert Enum to String
Enumerations, or enums are a convenient way to represent a fixed set of named values in programming. In PHP, native support for enums was introduced in PHP 8.1. If you are working with an earlier version of PHP, or if you want to explore alternative approaches, you may need a way to convert enums to strings. Table of Content Using Class ConstantsAs
2 min read
PHP Program to Convert String to ASCII Value
Given a String the task is to convert the given string into ASCII code using PHP. ASCII is the American Standard Code for Information Interchange, which is a widely used standard for encoding characters in computers and digital communication systems. There are two methods to convert a given String into ASCII code, these are as follows: Table of Con
2 min read
How to Convert String to Camelcase in PHP?
Given a String containing spaces, the task is to Convert String to Camelcase in PHP. Converting a string to CamelCase is a common operation in PHP, especially when working with variable names or class names. CamelCase is a naming convention where the first letter of each word in a compound word is capitalized except for the initial word. In this ar
3 min read
How to Convert a String to JSON Object in PHP ?
Given a String, the task is to convert the given string into a JSON object in PHP. JSON (JavaScript Object Notation) is a widely used data interchange format. PHP provides convenient functions to work with JSON data. Table of Content Using json_decode() to Convert to an ArrayHandling Errors with json_last_error() and json_last_error_msg() MethodsUs
3 min read
How to convert uppercase string to lowercase using PHP ?
Converting an uppercase string to lowercase means changing all capital letters in the string to their corresponding small letters. This is typically done using programming functions or methods to ensure uniformity in text formatting and comparison. Below we have some common approaches Table of Content Using strtolower()Using mb_strtolower() Functio
2 min read
How to convert lowercase string to uppercase using PHP ?
A string is a storage object in PHP comprising characters, numbers or special symbols. Strings in PHP are case-sensitive. The interconversion between lower and upper case can be easily done using various in-built methods in PHP. Table of Content Using chr() method Using strtoupper() method Using mb_convert_case() functionUsing preg_replace_callback
4 min read
How to convert a String into Number in PHP ?
Strings in PHP can be converted to numbers (float/ int/ double) very easily. In most use cases, it won't be required since PHP does implicit type conversion. This article covers all the different approaches for converting a string into a number in PHP, along with their basic illustrations. There are many techniques to convert strings into numbers i
4 min read
How to convert DateTime to String using PHP ?
Converting a `DateTime` to a string in PHP involves formatting the `DateTime` object into a human-readable format using the `format()` method. This process allows you to represent dates and times as strings in various formats, such as Y-m-d H:i:s. There are some following approaches Table of Content By using the Format Method By using list() Method
4 min read
How to convert an Integer Into a String in PHP ?
The PHP strval() function is used to convert an Integer Into a String in PHP. There are many other methods to convert an integer into a string. In this article, we will learn many methods. Table of Content Using strval() function.Using Inline variable parsing.Using Explicit Casting.Using sprintf() FunctionUsing concatenation with an Empty StringUsi
3 min read
How to convert String to Float in PHP ?
Converting a string to a float in PHP is a common requirement when handling numeric data stored in string format. This conversion allows the numeric string to be used in calculations or comparisons, ensuring accurate manipulation of data within the program. There are many methods to convert a string into a number in PHP, some of them are discussed
3 min read
How to convert Integer array to String array using JavaScript ?
The task is to convert an integer array to a string array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. Approaches to convert Integer array to String array:Table of Content Approach 1: using JavaScript array.map() and toString() methodsApproach 2: Using JavaScript Array.join() and split() methodsAp
2 min read
How to convert array to SimpleXML in PHP
Many times need to store the data as a XML format into the database or into the file for later use. To fulfill this requirement need to convert data to XML and save XML file. The SimpleXML extension functions provides the tool set to convert XML to an object. Those objects deals with normal property selectors and array iterators. Example 1: PHP Cod
3 min read
How to convert an array into object using stdClass() in PHP?
To convert an array into the object, stdClass() is used. The stdClass() is an empty class, which is used to cast other types to object. If an object is converted to object, its not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty. Example 1: I
3 min read
How to convert XML file into array in PHP?
Given an XML document and the task is to convert an XML file into PHP array. To convert the XML document into PHP array, some PHP functions are used which are listed below: file_get_contents() function: The file_get_contents() function is used to read a file as string. This function uses memory mapping techniques which are supported by the server a
2 min read
Convert multidimensional array to XML file in PHP
Given a multi-dimensional array and the task is to convert this array into an XML file. To converting the multi-dimensional array into an xml file, create an XML file and use appendChild() and createElement() function to add array element into XML file. Example: First, create a PHP Multidimensional Array for converting that array into the XML file
2 min read
How to convert PHP array to JavaScript or JSON ?
PHP provides a json_encode() function that converts PHP arrays into JavaScript. Technically, it is in JSON format. JSON stands for JavaScript Object Notation. Statement: If you have a PHP array and you need to convert it into the JavaScript array so there is a function provided by PHP that will easily convert that PHP array into the JavaScript arra
2 min read
How to convert array values to lowercase in PHP ?
Given an array containing uppercase string elements and the task is to convert the array elements (uppercase) into lowercase. There are two ways to convert array values to lowercase in PHP. Using foreach loopUsing array_map() function Using foreach loop: In this approach, an iterator iterates through the value of an array individually and convert e
2 min read
How to convert an array to CSV file in PHP ?
To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on fa
2 min read
How to Convert Byte Array to JSON in PHP ?
Given a Byte Array, the task is to convert Byte Array into JSON using PHP. Converting a byte array to JSON in PHP is a common task, especially when dealing with binary data or when you want to represent raw data in a JSON format. Table of Content Using base64_encode() and json_encode() FunctionsUsing Custom Conversion FunctionApproach 1: Using base
2 min read
How to Convert Number to Character Array in PHP ?
Given a number, the task is to convert numbers to character arrays in PHP. It is a common operation when you need to manipulate or access individual digits of a number. This can be particularly useful in situations where you need to perform operations on the digits of a number, such as digital root calculations, digit summing, or validations. Below
3 min read
Convert an object to associative array in PHP
An object is an instance of a class. It is simply a specimen of a class and has memory allocated. The array is the data structure that stores one or more similar types of values in a single name but an associative array is different from a simple PHP array. An array that contains a string index is called an associative array. It stores element valu
3 min read
How to Convert File Content to Byte Array in PHP ?
Converting file content to a byte array in PHP is a useful technique for various applications, including file manipulation, data processing, and when working with binary files like images or PDFs. PHP offers multiple ways to read file content and convert it into a byte array, providing flexibility to handle different scenarios effectively. Using fi
6 min read
How to convert a normal string to a uppercase string using filter in VueJS ?
Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js templ
2 min read
three90RightbarBannerImg