PHP and MySQL (54 Blogs) Become a Certified Professional

How to Convert a String to Array in PHP

Published on Oct 30,2019 142 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

PHP provides functions that convert from strings to arrays. In this article, we will understand how to convert a String to Array in PHP in the following order:

 

An Introduction to convert a String to Array

The preg_split function provides options to control the resulting array and uses a regular expression to specify the delimiter. The explode function splits the string where it finds the delimiter you specify. A string can also be an array of characters to some extent.

Explode Method

Pass a delimiter and a string to the explode function, and it splits the string into array elements, where it finds the delimiter. The delimiter can be a single character or it can be multiple characters.

String to Array in PHP

A string contains a list of items separated by a space and comma. Explode function is used to convert the list to an array by passing a delimiter string consisting of a comma and space (‘, ‘) as the first argument. Passing the string to convert as the second argument:

// string to convert
$fruits = ‘apple, orange, pear, banana, raspberry, peach’;
$fruits_ar = explode(‘, ‘, $fruits);
Var_dump($fruits_ar);
{
[0]=>
String(5) “apple”
[1] =>
String(6) “orange”
[2] =>
String(4) “pear”
[3] =>
String(6) “banana”
[4] =>
String(9) “raspberry”
[5] =>
String(5) “peach”
}
*/

In the next example a forward slash (/) as a delimiter to split a pathname into an array of directories:

$dirs = explode(‘/’, $path);
Var_dump($dirs);
{
[0] =>
String(0) “”
[1] =>
String (4) “home”
[2] =>
String (8) “someuser”
[3] =>
String (9) “documents”
[4] =>
String(5) “notes”
[5] =>
String(4) “misc”
[6] =>
String(0) “”
}
*/

The result shows the first element and the last element in the array contains empty strings because nothing precedes the last forward slash or the first forward slash. The original string is split at the points creating array elements.

If the delimiter string is not found within the string, an array of one element will be returned, and element will contain the entire string. The explode function provides an optional limit parameter.

The preg_split function also uses a regular expression to specify the delimiter. Preg_split also provides options that give more control over the array returned.

 

Str_split Method

It converts the string argument to an array with elements of equal length. We can pass a length as the second argument, or it will default to 1. In the below example , we pass 3 to create an array whose elements have three characters each:

$str = ‘abcdefghijklmnopqrstuvwxyz’;
$split = str_split($str, 3);
Print_r($split);
{
[0] => abc
{1} => def
[2] => ghi
[3] => jkl
[4] => mno
[5] => pqr
[6] => stu
[7] => vwx
[8] => yz
}
*/

In the array, the last entry contains the remaining characters, even if fewer than the length argument specifies.

 

Str_word_count

The str_word_count function converts a string to an array of words when passed a second argument.

 

Strings as Arrays of Characters

Strings are not really arrays, but can access the characters in a string using array syntax, as the following demonstrates:

$str = ‘top dog’;
Echo $str[2];

$str[2] = ‘y’;
Echo $str;

Display the results using echo and set it to a new value.

We can access individual characters in a string using a for a loop. We demonstrate by using a for loop to see how many times the letter ‘a’ occurs in the example string:

$str = ‘An example string’;
$count = 0;
For ($i=0, $len=strlen($str); $i<$len; $i++ ) {
If ( strops(‘Aa’, $str[$i]) !== false ) {
$count++;
}
}
Echo $count; //2

In the for loop, we inspect each character, in turn, using the strops function to check if it is ‘aA’. We increment the $count variable. Displaying echo once outside the for a loop.

A string can be treated as an array of characters to some degree.

 

With this, we come to the end of String to Array in PHP article. I hope you got an idea of how to convert a string to an array.

Check out the PHP Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section of ”String to Array in PHP” and I will get back to you.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.