PHP Function Explode Manual and Examples

When we program in PHP and work with strings, it is essential to know a series of functions that are repeated in our code over and over again.

Among them you may know str_replace, strpos either substr. And the function that we will discuss next is one more of this repertoire: the PHP function explode().

If you don’t know its functionality, it may sound familiar to you split()a function that does not exist in php but has the same functionality.

With this tutorial I want you to become an expert. So I propose you:

  1. definition of a Explode() PHP.
  2. Explode PHP to pass from a Text to an Array.
  3. Use an Explode and at the same time extract a position.

Content

  • Defining the Explode() function
    • basic example
  • Examples of EXPLODE in PHP
    • Examples of Explode and at the same time extract a position
    • foreach and explode example
  • Observations and errors with the function explode

Defining the Explode() function

The function PHP Explode uses three input parameters for its configuration:

  • The delimiter: here we will indicate the symbol or text to be used to make the “cut” in the text.
  • The text string to cut: this is the text string that will be traversed to cut and form the result array.
  • A limit of cuts (OPTIONAL): if we use this field we will indicate the maximum number of positions that the resulting array will have. The last position of the array will contain all the text remaining from where you stopped cutting.

The syntax of explode in php I would be:

<?php
explode(separator,string,limit)
?>

basic example

Thus a complete call and a very simple example of the explode function could be:

<?php
$array = explode( '/', '/funcion/explode-php', 3);
?>

Examples of EXPLODE in PHP

The function explode exists to transform text strings or strings in PHP arrays.

Thanks to her, in a very simple way, we can pass any text string, no matter how long, to a array php at our choice.

For example, we could cut any text by the blank spaces, we would thus obtain a array of his words:

<?php
$texto = 'Cortamos cadena de texto con explode-php en srCodigoFuente';
$array = explode( ' ', $texto );
foreach ( $array as $palabra ){
	echo $palabra . ' <br>';
}
?>

This small code would print on the screen one by one all the words of the text contained in $text.

Cortamos
cadena
de
texto
con
explode-php
en
srCodigoFuente

Keep in mind that although I do not show it in the example, the keys or keys for each word are numeric and order: 1,2,3…

On the other hand, using the third parameter of explode() we could have taken only the first 3 words and left the rest in the last position of the Array:

<?php
$texto = 'Cortamos cadena de texto con explode-php en srCodigoFuente';
$array = explode( ' ', $texto, 3 );
foreach ( $array as $palabra ){
	echo $palabra . ' <br>';
}
?>
//resultado:
Cortamos
cadena
de
texto con explode-php en srCodigoFuente

Or with a var_dump() you would get:

<?php
$texto = 'Cortamos cadena de texto con explode-php en srCodigoFuente';
$array = explode( ' ', $texto, 3 );
var_dump($array);
?>
//resultado:
array(4)
(
    [0] => string(5) "Cortamos"
    [1] => string(5) "cadena"
    [2] => string(5) "de"
    [3] => string(5) "texto con explode-php en srCodigoFuente"
)

Examples of Explode and at the same time extract a position

This last point is rather a review for something normal in programming.

But since you may not know it, I would like to leave it here as it is a little trick that works very well.

I’m going to slice and extract any position from a string on a single line:

<?php
$texto = 'tutorial sobre explode php';
$palabra3 = explode(' ', $texto)[2];
echo 'La tercera palabra es: ' . $palabra3;
?>
//RESULTADO:
La tercera palabra es: explode

Like any trick, you must use it wisely (I know I have a bit of Yoda left), and keep in mind that if you use it, it is because you expect that position to exist.

That is to say, If the position you indicate does not exist, you will have made a mistake.

foreach and explode example

Now an example with foreach and explode, a combination that is a classic for any backend php developer:

<?php
$texto = 'Cortamos cadena de texto con explode-php en srCodigoFuente';
$sql = '';
foreach( explode(' ', $texto) as $palabra ){
       $sql = 'INSERT INTO palabra (palabra, fecha) VALUES ( '.$palabra.',  '.date('Y-m-d').' );';
}
$db->execute($sql); //$db sería un objeto previamente creado para ejecutar consultas contra mysql
<?php

Observations and errors with the function explode

  • You will receive an error if the indicated separator is a empty string.
  • If the text string ends in the separator character you will receive an array with a blank position.
  • If he string begin with the separator character you will receive an array with an empty value in the first position.
  • You can indicate a positive limit or negativeif you indicate the latter, you will receive all the components except the last “limit” elements (I call each block separated by the separator element.
  • It’s compatible with PHP 4, 5, 7 and 8.

Leave a Reply