PHP explode () with spaces

0

I have the following code:

$pal = "botella, frasco, recipiente, bandeja, plato, barril";
$pal = explode(",",$pal);

My question is, if there is a space after each comma present, can you leave the explode as it is or should you place "," instead of "," ?

    
asked by Máxima Alekz 04.12.2016 в 04:22
source

1 answer

2

It will depend on how you want the elements stored in your array.

If you want to generate an array simply with the names of the elements (without spaces at the beginning of each element) you should use ", " :

With this code:

$pal = "botella, frasco, recipiente, bandeja, plato, barril";
$pal = explode(", ",$pal);
print_r($pal);

You would get the following output:

Array
(
    [0] => botella
    [1] => frasco
    [2] => recipiente
    [3] => bandeja
    [4] => plato
    [5] => barril
)

If instead you want to keep that space at the beginning of each element then you should use "," :

With this code:

$pal = "botella, frasco, recipiente, bandeja, plato, barril";
$pal = explode(",",$pal);
print_r($pal);

You would get the following output:

Array
(
    [0] => botella
    [1] =>  frasco
    [2] =>  recipiente
    [3] =>  bandeja
    [4] =>  plato
    [5] =>  barril
)

As you can see, in this second case the space is maintained at the beginning of the elements.

    
answered by 04.12.2016 / 05:01
source