Programs

String to Array in PHP: List of Functions Used

PHP is a powerful scripting language used for creating static, dynamic, and interactive web pages. It is embedded in HTML and manages web applications, databases, and session tracking.

A string is an array of characters. PHP works on strings and converts them to arrays with the help of some built-in functions.

In this article, we will look at some of the important functions of converting a string to an array in PHP. We will look at each PHP function and see how it is written in the program.

Check out our free courses to get an edge over the competition

Why is it Necessary to Convert String to Array in PHP?

In many cases, an array is preferable to a string. For example, before storing the passwords in the database that the users enter in a web app, they can be converted into an array. Access to the data is made easier and more secure as a result. You can use arrays to achieve faster operations and better data organisation. PHP, a robust programming language, has several built-in methods for converting a string to an array.

Functions used to Convert String to Array in PHP

There are basically four functions to convert String to Array in PHP:

  1. str_split()
  2. preg_split()
  3. chunk_split()
  4. explode()
  • The str_split function splits a string into array elements with the same length.
  • The preg_split function specifies the delimiter and controls the resultant array with the help of a regular expression.
  • The explode function splits the string when a delimiter is found.
  •  The chunk_split() function splits a string into smaller parts without altering the original string.

Check out upGrad’s Advanced Certification in Cloud Computing 

Let’s implement each of these functions and see how they convert String to Array in PHP.

1. str_split()

str_split function converts a string to an array in PHP. It splits into bytes, rather than characters with a multi-byte encoded string.

Syntax

str_split ( $string , $length )

Parameters

String – The given Input string.

Length – The maximum string length.

If the length is mentioned, the returned array breaks down into chunks of that length number, else, the chunk length of each will be by default, one character.

If the measure of length is more than the length of the string, the complete string returns as the first array element.


upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Check out upGrad’s Advanced Certification in Cyber Security

Example

<?php

$str = "PHP String ”;

$arr1 = str_split($str);

$arr2 = str_split($str, 3);

print_r($arr1);

print_r($arr2);

?>

Output

It will be in the form of Array

Array

(

[0] => P

[1] => H

[2] => P

[3] => 

[4] => S

[5] => t

[6] => r

[7] => i

[8] => n

[9] => g

[10] => 

)

Array

(

[0] => PHP

[1] =>  St

[2] => rin

[3] => g

)

Explore Our Software Development Free Courses

2. preg_split()

preg_split is a function that splits a string using a regular expression.

Syntax

preg_split ( $pattern ,  $subject ,  $limit ,  $flags )

Parameters

Pattern – The string pattern to be searched.

Subject – The input string.

Limit – Substrings up to the limit value specified. A -1 or 0 means “no limit”.

Flags – If this flag is set, the appendant string offset is returned.

Example

<?php

$string = preg_split("/[\s,]/", "hypertext programming language ");

print_r($string);

?>

Output

Array

(

[0] => hypertext

[1] => programming

[2] => language

)

Explore our Popular Software Engineering Courses

3. chunk_split()

chunk_split is a function that splits a string into a smaller chunk and returns a chunked string as an output.

Syntax:

chunk_split( $string , $length , $separator = “\r\n” )

Parameters

String: The string to be chunked.

Length: The length of the chunk.

Separator: The ending line sequence.

Example

<?php

$str = "Hello World!";

echo chunk_split($str,1,".");

?>

Output

H.e.l.l.o. .w.o.r.l.d.!.

In-Demand Software Development Skills

4. explode()

 explode is a PHP function that splits a string by a string. It is faster than the preg_split() function and is binary-safe.

Syntax:

explode ( $separator ,$string ,$limit)

Parameters

Separator: The string at the boundary.

String: The input string.

Limit: Specifies the length of the output string

If the limit is set to be a positive value, the returned array will be the maximum limit of elements with the last element having the remnant string.

If the limit is a negative value, all the string components excluding the last –limit are returned.

If the limit is zero, then it is assumed as 1.

The explode function splits the string parameter on boundaries limited by the separator and returns an array. If the separator is an empty string (“), it returns a false value.

If the separator consists of some value that is not the part of the string and a negative limit is used, an empty array is returned, else an array of the string will be returned.

Example

<?php

$input1 = "hello";

$input2 = "hello,world";

$input3 = ',';

print_r( explode( ',', $input1 ) );

print_r( explode( ',', $input2 ) );

print_r( explode( ',', $input3 ) );

?>

Output

array(1)

(

[0] => string(5) “hello”

)

array(2)

(

[0] => string(5) “hello”

[1] => string(5) “there”

)

array(2)

(

[0] => string(0) “”

[1] => string(0) “”

)

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Read our Popular Articles related to Software Development

Another Method To Convert A String To An Array In PHP

You can convert string to array in PHP in several ways. Some of them are as follows.

Manually Looping Through String

  • Manually looping through the string is a technique on this list for turning a string into an array in PHP. 
  • Initialising a variable to zero, let’s say “i,” you’ll then begin a loop from “i” and continue it until “i” is shorter than the length of the string. 
  • You will increment the variable “i” and store each word of the string in the array inside the loop.
Below is the code for the same:

<?php

    $the_str = 'lorem ipsum';    

    $the_ar = [];

    for ($i = 0; $i < strlen($the_str); $i++) {

      if ($the_str[$i] != " ") { 

        $the_ar[] = $the_str[$i]; 

      }}

    echo "Final converted array: <br>";

    print_r($my_array); // l, o, r, e, m, i, p, s, u, m 

Creating a Multidimensional Array from a String

Use the explode() function multiple times to create a multidimensional array. Consider the following example: 

String: “Peter,Jacob,31”

Here the comma separates the name and age values. Using the explode() function, you can split the string into an array. Using explode() again on the first element, you can split it into an array based on the delimiter used to separate the first and last names. 

$str = "Peter,Jacob,31";

$arr1 = explode(",", $str); // $arr1 is now ["Peter", "Jacob", "31"]

$name = explode(" ", $arr1[0]); // $name is now ["Peter", "Jacob"]

$age = $arr1[2]; // $age is now "31"

$newArr = [

    "first_name" => $name[0],

    "last_name" => $name[1],

    "age" => $age

];

This code creates a new multidimensional array $newArr as shared below: 

[    “first_name” => “Peter”,    “last_name” => “Jacob”,    “age” => “31”]

Conclusion

String to Array in PHP is a very important operation as it splits a string into an array of characters. In this article, we have demonstrated the process of string conversion to an array with the help of four PHP functions: str_split, preg_split, chunk_split and explode. We have also shown the example for each function showing how it is performed and will give an output. 

Programming with PHP needs skills to be learned and is a must for every PHP programmer. upGrad’s Master of Science in Computer science is a carefully created course where you will learn in-demand skills and perceive growth in your Software Development career journey.

What are strings in PHP?

You can think of strings as arrays of characters. Strings are commonly used in PHP for storing words and sentences. Strings are also used in PHP for data exchange. That is, strings are used to pass data from one page to another page. Strings in PHP can be found in almost all programs, as most of the tasks are done with the help of strings. Strings are very easy to work with and are easy to use in PHP. The syntax is to enclose the string in double quotation marks. You can also use single quotation marks, but this is not recommended, as there might be instances when using single quotation marks might cause problems in the script.

What are arrays in PHP?

Arrays are considered one of the most useful features in PHP. An array allows you to store multiple values in one variable. Arrays are indexed numerically, similar to an associative array in Perl. However, unlike Perl, you cannot assign values to these indexes. Arrays in PHP are just collections of variables that you can access with one variable name. By default, PHP arrays are ordered. This means that you can access specific elements using the array name and the element's index (position) in the array.

What are the applications of PHP?

PHP is a server-side programming language, which means that it is used on the server side to create dynamic Web pages. It is used to process user input and return a Web page. It can be used to create Web sites, build online forms and validate data and generate dynamic Web pages. PHP enables the websites to store data on server and retrieve the data whenever required. It is the most powerful tool used to develop dynamic web sites. Some of the most popular and widely used applications are WordPress, Facebook, WordPress, Kickstarter and Drupal.

Want to share this article?

Become a Full Stack Developer

Leave a comment

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

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks