0

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?

3
  • Maybe declare the string newresultado first. Commented Jan 3, 2018 at 17:48
  • Try removing the [0] from the foreach, you are iterating over the elements then looking for a brand. Commented Jan 3, 2018 at 17:52
  • Did you give up? Commented Jan 29, 2018 at 18:27

2 Answers 2

1

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');
Sign up to request clarification or add additional context in comments.

Comments

0

Try removing [0] from $testarray.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.