Convert string to array in PHP

How to convert a string to array in PHP

Posted by Luke Beeno on November 29, 2022

Convert string to array in PHP

How to convert a string to array in PHP

Posted by Luke Beeno on November 29, 2022

Here is how you can convert a string to an array.

Use the explode() as below:

$str = "Welcome to the WeCode101 platform";
var_dump(explode(" ",$str));

Result:

array(5) {
  [0]=>
  string(7) "Welcome"
  [1]=>
  string(2) "to"
  [2]=>
  string(3) "the"
  [3]=>
  string(9) "WeCode101"
  [4]=>
  string(8) "platform"
}

The first parameter in the method is the break point in the string and the second parameter is the string itself.

Here is an example where the break point are hyphen:

$str = "Welcome-to-the-WeCode101-platform";
var_dump(explode("-",$str));

Result:

array(5) {
  [0]=>
  string(7) "Welcome"
  [1]=>
  string(2) "to"
  [2]=>
  string(3) "the"
  [3]=>
  string(9) "WeCode101"
  [4]=>
  string(8) "platform"
}

You can even decide on the amount of segments or items you require in the array by adding a third param.

$str = "Welcome-to-the-WeCode101-platform";
var_dump(explode("-",$str, 3));

Result:

array(3) {
  [0]=>
  string(7) "Welcome"
  [1]=>
  string(2) "to"
  [2]=>
  string(22) "the-WeCode101-platform"
}

 

Any question?
This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question