i am trying to expolde string but why i get 8 times result .... please tell me how i can solve this (please not give me suggstion about using for each loop i am already know that) <?php $a='Madhuri Dixit,Konkona Sen Sharma,Kunal Kapoor,Divya Dutta,Ranvir Shorey,Vinay Pathak,Jugal Hansraj,Yashpal Sharma,Raghuveer Yadav'; $pieces = explode(",", $a); $letter_count = substr_count($a, ','); for ($i=1; $i<=$letter_count; $i++) { $pieces = explode(",", $a); echo $pieces[0].'</br>'; echo $pieces[1].'</br>'; echo $pieces[2].'</br>'; echo $pieces[3].'</br>'; echo $pieces[4].'</br>'; echo $pieces[5].'</br>'; echo $pieces[6].'</br>'; echo $pieces[7].'</br>'; echo $pieces[8].'</br>'; echo $pieces[9].'</br>'; } ?> Result
Hello, Try this <?php $a='Madhuri Dixit,Konkona Sen Sharma,Kunal Kapoor,Divya Dutta,Ranvir Shorey,Vinay Pathak,Jugal Hansraj,Yashpal Sharma,Raghuveer Yadav'; $pieces = explode(",", $a); echo "<pre>"; print_r($pieces); echo "</pre>"; ?>
For 9 times (your for loop) you echoed all 9 names. The program was doing exactly what you told it to. <?php $a='Madhuri Dixit,Konkona Sen Sharma,Kunal Kapoor,Divya Dutta,Ranvir Shorey,Vinay Pathak,Jugal Hansraj,Yashpal Sharma,Raghuveer Yadav'; $pieces = explode(",", $a); echo $pieces[0].'</br>'; echo $pieces[1].'</br>'; echo $pieces[2].'</br>'; echo $pieces[3].'</br>'; echo $pieces[4].'</br>'; echo $pieces[5].'</br>'; echo $pieces[6].'</br>'; echo $pieces[7].'</br>'; echo $pieces[8].'</br>'; echo $pieces[9].'</br>'; ?> PHP: would do what you want. So would <?php $a='Madhuri Dixit,Konkona Sen Sharma,Kunal Kapoor,Divya Dutta,Ranvir Shorey,Vinay Pathak,Jugal Hansraj,Yashpal Sharma,Raghuveer Yadav'; $pieces = explode(",", $a); $letter_count = count($pieces); $pieces = explode(",", $a); for ($i=1; $i<=$letter_count; $i++) { echo $pieces[$i].'</br>'; } ?> PHP: (Never put code inside a loop if it can run outside the loop. You were counting how many elements there were in $pieces 9 times. Since the count is the same before the loop or inside it, do that outside the loop. It takes the same amount of time to calculate it each time, so you save 8 execution times that way.)
Thanks Rukbat for this .... now i am understand little addition : for ($i=0; $i<=$letter_count; $i++)