Heapcoding

PHP explode Function, Best Practice, Usage With Examples

Published August 8, 2020

PHP explode

PHP is a very powerful language that is used to develop server-side web applications.

And php explode is the php function that is used to break or convert a string into array.

Let’s take a look to an example how php explode function works.

<?php
$str = "Welcome to my website Heapcoding.";
print_r (explode(" ",$str));
?>

The above code will generate the following output.

Array ( [0] => Welcome [1] => to [2] => my [3] => website [4] => Heapcoding. )

Let’s discuss the above example.

<?php

This is the starting tag of php script in which we start writing php code.

$str

This is the php veriable where the value “Welcome to my website Heapcoding.” stored.

print_r()

This is the php function through which we print the object for better visualization.

explode(” “,$str)

Here is our main php explode function which takes two parameters.

  1. First argument is separator that defines from where we need to break string and convert to array element.
  2. Second argument is the actual string to which we want to break into array.

PHP explode definition and usage

The explode function is used to break a string into an array.

Note: The separator couldn’t be an empty string.

Note: PHP explode function is binary-safe.

Syntax

explode(separator,string,limit)

Parameters & Values

ParameterDescription
SeparatorThis is required parameter which specifies from where to break string and convert to array element.
StringThis is required parameter which is the main string that needs to be converted into array.
LimitThis is optional parameter that specifies how much number of array elements you want to return in output.
Possible Values:
1. Greater than 0: Returns an array with the maximum number of limit element(s).
2. Less than 0: Returns an array except for the last limit elements.
3. 0: Returns an array with only one element.

Technical Details

Return ValueReturns an array of strings.
PHP Version4+
ChangelogThe PHP parameter was added when PHP version 4.0.1 was released and support for negative limits was added when PHP version 5.1.0 was released

You may also like: