Page 1 sur 1

Automatiser un contrôle if et elseif

Posté : 05 mars 2017, 13:18
par yule
Bonjour

Comment simplifier mon contrôle et l'automatiser indépendament du nombre de keywords
le but est d'ajouter un + devant chaque keywords présent
$arr = explode(' ', $keywords); 
		$wrdCount = str_word_count($keywords);
	
		if($wrdCount == 1) {
		$out = '+'.$arr[0].'';
		} elseif ($wrdCount == 2) {
		$out = '+'.$arr[0].'+'.$arr[1].'';
		} elseif ($wrdCount == 3) {
		$out = '+'.$arr[0].'+'.$arr[1].'+'.$arr[2].'';
		} elseif ($wrdCount == 4) {
		$out = '+'.$arr[0].'+'.$arr[1].'+'.$arr[2].'+'.$arr[3].'';
		} elseif ($wrdCount == 5) {
		$out = '+'.$arr[0].'+'.$arr[1].'+'.$arr[2].'+'.$arr[3].'+'.$arr[4].'';
		} elseif ($wrdCount == 6) {
		$out = '+'.$arr[0].'+'.$arr[1].'+'.$arr[2].'+'.$arr[3].'+'.$arr[4].'+'.$arr[5].'';
		} elseif ($wrdCount == 7) {
		$out = '+'.$arr[0].'+'.$arr[1].'+'.$arr[2].'+'.$arr[3].'+'.$arr[4].'+'.$arr[5].'+'.$arr[6].'';
		}
etc......

D'avance merci
Yule

Re: Automatiser un contrôle if et elseif

Posté : 05 mars 2017, 14:21
par finipe
Une boucle "for" fera très bien l'affaire :

Code : Tout sélectionner

$arr = explode(" ", $keywords); $wrdCount = str_word_count($keywords); $out = ""; for($i=0 ; $i<$wrdCount ; $i++) { $out .= "+".$arr[$i]; }

Re: Automatiser un contrôle if et elseif

Posté : 05 mars 2017, 14:33
par yule
Parfait merci bien !

Re: Automatiser un contrôle if et elseif

Posté : 05 mars 2017, 18:02
par finipe
Un p'tit coup de "résolu" est ce sera top ;)

Re: Automatiser un contrôle if et elseif

Posté : 06 mars 2017, 09:19
par Spols
un strtr ferait aussi bien l'affaire, et ce sera plus rapide
$out = '+'.strtr(' ','+',$keywords);