david212 Posted February 17, 2009 Share Posted February 17, 2009 Hello! Im a newbie on php and I have a problem with arrays. I have 4 strings using arrays (something like this: $a = array("nick","room","id","channel"); and i try to put on every first letter of this array strings the different color, for example, "color=red". I tried to do using for loop: <?php $a = array("nick","room","id","channel"); $s=sizeof($a); for($i=0;$i<$s;$i++){ echo($a[$i]."<br>"); if($i%2==0) { echo("<span style="color:red;">".($a[$s])."</span>"); } } ?> and the result must be something like this: nick room id channel but it does nothing! Can anyone help me? Thanx Link to comment https://forums.phpfreaks.com/topic/145524-solved-problems-with-array/ Share on other sites More sharing options...
Mchl Posted February 17, 2009 Share Posted February 17, 2009 Sure Your code does not work, because $s is not defined, so $i < $s in for loop always fails There are also other issues with your code I'd do it this way $a = array("nick","room","id","channel"); foreach($a as $word) { echo "<span style=\"color:red;\">".substr($word,0,1)."</span>".substr($word,1); } should work, though I didn't test it. See foreach and substr in manual to see how they work Link to comment https://forums.phpfreaks.com/topic/145524-solved-problems-with-array/#findComment-764025 Share on other sites More sharing options...
david212 Posted February 17, 2009 Author Share Posted February 17, 2009 Thank you Link to comment https://forums.phpfreaks.com/topic/145524-solved-problems-with-array/#findComment-764032 Share on other sites More sharing options...
david212 Posted February 18, 2009 Author Share Posted February 18, 2009 Thank you sorry, i have a question, why this code doesn't work?Could you tell me? I've tried to convert your function in for loop <?php $a = array("nick","room","idle","channel"); $s=sizeof($a); for($i=0;$i<$s;$i++) { $s2=strlen($a[$i]); if($s2%2==0){ echo("<span style=\"color:red;\">".$a[$i][($s2)-4]."</span>"); } echo($a[$i]."<br>"); } ?> the result i recieve is: nnick rroom iidle channel and the result must be the same which in the function you created. Thank you Link to comment https://forums.phpfreaks.com/topic/145524-solved-problems-with-array/#findComment-765116 Share on other sites More sharing options...
Mchl Posted February 18, 2009 Share Posted February 18, 2009 I just have no idea why you're overcomplicating things like this.... This echo($a[$i]."<br>"); displays whole word, but you need to drop the first letter, as you have already displayed it. good luck Link to comment https://forums.phpfreaks.com/topic/145524-solved-problems-with-array/#findComment-765267 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.