user1895377
user1895377

Reputation: 201

PHP - Foreach loop only echoing first letter of string

I have an array that looks like this:

array(1) { 
    ["brookybear"]=> array(5) { 
        ["id"]=> int(20217894) 
        ["name"]=> string(10) "Brookybear" 
        ["profileIconId"]=> int(603) 
        ["summonerLevel"]=> int(30) 
        ["revisionDate"]=> float(1397388011000) 
    } 
}

when i var_dump(); it. I'm trying to use a foreach loop to take the "name" value out of it. However, when I echo it, I only get "B" as the output, and not the full Brookybear.

Here is my foreach loop:

$url="APIURL";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
$array = json_decode($result, true);
foreach($array['brookybear'] as $champs)
{
echo $champs['name'];
}

Upvotes: 0

Views: 2447

Answers (3)

user3822721
user3822721

Reputation: 1

If first character is only display in string, you know what is the reason i now,

make sure array variable name is not same in your above script

. example

$my_var = "My name is umair";

and below you same use this variable for array

$my_var[0] = "My name is umair";

now if you echo array var it will show only first letter in output is "M" simply change the array variable than it will be working

Upvotes: 0

Seeinyou
Seeinyou

Reputation: 70

Why do you use loop to get the value? If I am doing this, I will simply write:

<?php
if ( isset( $array['brookybear']['name'] ) ) {
    echo $array['brookybear']['name'];
}

Upvotes: 0

willoller
willoller

Reputation: 7330

Looks like you're looping on the 'brookybear' item instead of the parent array.

If you want to see all the names of all the $champs:

$array = json_decode($result, true);
foreach($array as $champs)
{
    echo $champs['name'];
}

or more clearly:

$champions = json_decode($result, true);
foreach($champions as $champ)
{
    echo $champ['name'];
}

Upvotes: 2

Related Questions