Jump to content

for loop overwriting varible


cartesianbeef

Recommended Posts

Hi,

  probably a common problem but here goes:

 

What I want to do is take a word from a form and break it up into letters, then add ':' before and after each letter then save the entire array to the DB. I've got so far, it echoes fine, but the for loop overwrites the variable each time so I'm left with the last letter. Here's some example code:

 

<?php

$splitu = "hello World!";

for($i = 0; $i < strlen($splitu); $i++)

{

    $mess = ":".$splitu[$i].":";

    echo $mess;//this works fine, result is: :h::e::l::l::o:: ::W::o::r::l::D::!:

 

}

?>

<html><head>

 

<title><?=$mess?></title> //this just gives me :!:

 

</head>

 

<BODY BGCOLOR="#000000" TEXT="#ffffff" LINK="#ff0000" VLINK="#808080">

</body>

</html>

 

any help would be appreciated

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/153480-for-loop-overwriting-varible/
Share on other sites

maq, it worked... thank you! Could I ask what is it that the '.' did exactly?

 

It's the same thing as doing:

 

    $mess = $mess . ":".$splitu[$i].":";

 

A better example is with an arithmetic example:

 

$a = 2;

$b = 4;

$a += $b;

 

This is the same as $a = $a + $b;

guys - use the native functionality - its much more efficient.

 

looping over a string based on its length to 'split' it is what str_split does. the code is simpler (easier to manage) and far less work to achieve the same goals.

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.