PHP Basics

How can we convert a string value into an Array using PHP?

In php, a string can be converted into an array. PHP has a predefined function explode, which breaks string text into array.

String to Array Conversion

To convert a string into array lets use php function “Explode”

Syntax

explode(seperator, string);

Note: While converting a string into an Array by using explode php function, keep one important point always in your mind and that is, the separator plays an important role. In this example, I have used space as the separator. And if you have a string whose words are separated by comma, then use comma as separator.

Example

<?php

$fruitNameString=”apple, orange, grape, guava, mango”;

$fruitNames=explode(“, “,$fruitNameString); //explode function converted the string into an array

//lets print

foreach($fruitNames as $fruitName){

echo $fruitName.'<br/>’;  //echo each fruitname into next line

}

?>

output

apple

orange

grape

guava

mango