Comment transformer une chaîne de caractère en tableau en PHP

Vous pouvez utiliser la fonction explode() en PHP pour transformer ou diviser une chaîne en tableau par un séparation telle que espace, virgule, etc. Vous pouvez également définir le paramètre limit optionnel pour spécifier le nombre d’éléments de tableau à renvoyer.
 
 

Exemple :
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$str = 'Welcome to WayToLearnX.';
print_r(explode(" ", $str));
?>
<?php $str = 'Welcome to WayToLearnX.'; print_r(explode(" ", $str)); ?>
<?php
	$str = 'Welcome to WayToLearnX.';
	print_r(explode(" ", $str));
?>

Sortie :

Array
(
    [0] => Welcome
    [1] => to
    [2] => WayToLearnX.
)

 

Exemple avec le paramètre limit:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$str = 'Welcome to WayToLearnX.';
print_r(explode(" ", $str, 2));
?>
<?php $str = 'Welcome to WayToLearnX.'; print_r(explode(" ", $str, 2)); ?>
<?php
	$str = 'Welcome to WayToLearnX.';
	print_r(explode(" ", $str, 2));
?>

Sortie :

Array
(
    [0] => Welcome
    [1] => to WayToLearnX.
)
QCM sur PHP

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *