Convert string to Array

Welcome! In this article I am going to teach you functions to work texts and arrays being able to pass from one to the other easily.

Content

  • Convert a string to an Array
    • Example 1 explode php:
    • Example 1 explode php:
    • Example 2 String to Array
    • Limit of partitions when going from String to Array
  • Conclusion on EXPLODE PHP

Convert a string to an Array

To pass values ​​from String to Array type in PHP we can use the function explode. This function allows us cut the text string into smaller pieces, exactly by the character/s indicated as input parameter.

The definition of a PHP explode is:

array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )

Example 1 explode php:

In the following example we cut a text string into its words using the character blank space.

array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )

Example 1 explode php:

In the following example we cut a text string into its words using the character blank space.

<?php
$texto = 'Aprender a usar explode()';
$array = explode ( ' ', $texto );
foreach ( $array as $palabra ) {
     echo $palabra . '>br/<';
}
?>

departure from explode example 1:

Learn
to
wear
explode()

Example 2 String to Array

In this example I am going to cut the chain into pieces using the character “,”

<?php
$to_parse = 'palabras,para,separar';
$array = explode ( ',', $to_parse);
foreach ( $array as $palabra ) {
echo $palabra . '>br/<';
}
?>

Output of explode example 2:

words
for
pull apart

Limit of partitions when going from String to Array

We can also limit the number of partitions Which will perform the explode() function:

explode example 3: positive limit

<?php
$texto = 'Aprender/a/usar/explode()/con/limite';
//límite de tamaño del array positivo
$array_limitado = explode($texto, '/', 4);
foreach ( $array_limitado as $palabra ) {
	echo $palabra . '>br/<';
}
?>

Output of example 3:
Learn
to
wear
explode()

explode example 4: negative limit

If we indicate a negative limit the total size of the array the result will be the total size of the slices MINUS the negative number indicated:

<?php
$texto = 'Aprender/a/usar/explode()/con/limite';
$array_limitado = explode($texto, '/', -1);
foreach ( $array_limitado as $palabra ) {
	echo $palabra . '>br/<';
}
?>

Output from Negative Limit Example
Learn
to
wear
explode()
with

Conclusion on EXPLODE PHP

Well, how have you been? If you have understood it, I would appreciate it if you left a comment with, for example, Doubts or advice about cutting strings in PHP so that other visitors can also learn them.

Finally, I would ask you if you liked it, share the post or rate it (above) with 5 stars.

Thank you!

Leave a Reply