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
Share on other sites

You're not concatenating each letter with the surrounding ':' character.  You're always overwriting the last $mess with the new split element.  Change this line to: (notice the . )

 

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

Link to comment
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;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.