Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

String to Array in PHP: List of Functions Used

Updated on 16 June, 2023

7.74K+ views
7 min read

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

)

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

)

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.!.

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.

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.

Frequently Asked Questions (FAQs)

1. 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.

2. 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.

3. 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.

RELATED PROGRAMS