Lesson 9: Inbuilt and user defined functions:explode()

Recap: The previous function str_replace() returned a string as shown below:

<?php
$mystring  = "*188#1*3*3#";

//wherever there is a *, replace it with a #

echo str_replace("#","*",$mystring);
?>

Output: *188*1*3*3*

Now, suppose we want to extract the numbers 188,1,3 and 3 so that we can use the elsewhere, we will use the function explode()

The explode() function uses a selected separator to break a string into an array; (we will proceed with the code above)

Function syntax

explode(separator,string,limit) where;

separator :Required. Specifies where to break the string

string : Required. The string to split

limit :  Optional. Number of elements of an array to return

<?php

$mystring = “*188*1*2*”;

$result = explode(“*”,$mystring);

echo $result;

for ($i = 0; $i < count($result); ++$i) {
echo $result[$i] . " ";
}

?>

Output: array

This means that the return type of explode() is an array; we cannot print an array by just doing a PHP echo, now loop trough using ‘for’ control structure to print the array elements.
Suppose we want to remove the first array element, so that, the second element becomes the first one, the third becomes the second one……till the the nth element becomes the (n-1)th element; we use the array_shift() function to do this. We do this in the next lesson.
6 Comments

Add a Comment

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