php access array data misunderstanding

Given the following array $testarray:

array(1) {
  [0]=>
  array(3) {
    ["brand"]=>
    string(4) "fiat"
    ["year"]=>
    string(4) "2001"
    ["color"]=>
    string(4) "blue"
    }
}

I'm trying to access the data inside with:

foreach($testarray[0] as $key => $value)
{
    $newresultado = $value['brand'].$value['year'].$value['color'];
}
echo $newresultado;

I do not get an error returned, but I do get an empty string.

I checked a lot of topics and this should be correct. Why am I getting the empty string?

Upvotes: 0

Views: 52

Answers (2)

Mateusz Kibiłko
Mateusz Kibiłko

Reputation: 62

Try removing [0] from $testarray.

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

You are looping through the values under the 0 index so the indexes you are referencing don't exist. Also, if you have more than one then each will overwrite the other so you would use .= instead:

$newresultado = '';

foreach($testarray as $key => $value)
{
    $newresultado .= $value['brand'].$value['year'].$value['color'];
}
echo $newresultado;

If there will only ever be one item then there is no need to loop:

echo $testarray[0]['brand'].$testarray[0]['year'].$testarray[0]['color'];

You need to develop with these settings which would have shown you notices and errors:

error_reporting(E_ALL);
ini_set('display_errors', '1');

Upvotes: 1

Related Questions