Jump to content

[SOLVED] Problems with Array


david212

Recommended Posts

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

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

Thank you  ;D

 

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.