Jump to content

Recommended Posts

I'm trying to build an array in a foreach loop, but when I got to echo the results it only displays the first character of the string, but if I do a print_r on the array it show the data fine.

 

$msgColor1 = array();
foreach ($playerName1 as $value) {    
            $msgColor1['name'] .= $value[$i];
            $i = $i + 1;            
        }

 

print_r show the data but when i do

 

foreach ($msgColor1 as $test) {
            echo $test['name'];
}

Only shows the first character in the string

Link to comment
https://forums.phpfreaks.com/topic/217598-build-array-in-foreac-loop/
Share on other sites

Modify your code to reflect it.

 

$msgColor1 = array();
foreach ($playerName1 as $value) {    
            $msgColor1['name'] .= $value[$i]; //<- you are referencing value as an array, which would split the string by characters.  remove the [$i], and you are good to go.
            $i = $i + 1;            
        }

 

So it should read.

$msgColor1 = array();
foreach ($playerName1 as $value) {    
            $msgColor1['name'] .= $value;
            $i = $i + 1;            
        }

Are you trying to store all of the player names in an multi-dimensional array? So that msgColor1 is an array and has an array inside of it with the key named "name" and each value of the array "name" has each of the player names?

 

If that's the case:

foreach($playerName1 AS $value){
    $msgColor1['name'][] = $value;
}

 

And calling print_r on msgColor1 will give you an output of something similar to:

 

Array
(
    [name] => Array
        (
            [0] => johnny
            [1] => bob
            [2] => malcolm
        )

)

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.