-4

I have a php array that looks like this...

(
    [name] => Tester
    [colors] => Array
        (
            [blue] => Array
                (
                    [count] => 1
                    [status] => hold
                )

        )
)

I am trying to get the first array from colors but have not been able to. I have tried...

echo $array['colors'][0];
echo $array->colors[0];

Neither of which have given me any results. Where am I going wrong?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • I suppose you named your variable $array? – GlennM Mar 18 '21 at 12:01
  • 1
    $array['colors']['blue'] – Anurat Chapanond Mar 18 '21 at 12:04
  • Does this answer your question? [How to get the first item from an associative PHP array?](https://stackoverflow.com/questions/1617157/how-to-get-the-first-item-from-an-associative-php-array) – El_Vanja Mar 18 '21 at 12:12
  • _“Where am I going wrong?”_ - if we were to assume that you did not need to make an effort to learn any basics ever, because you can always just coming running to this community and have it fix whatever trivial problem you have now again for you, then nowhere … But I personally would strongly disagree on that premise to begin with. – CBroe Mar 18 '21 at 12:26
  • I would recommend reading through the [manual page](https://www.php.net/manual/en/language.types.array.php) about arrays. It's pretty extensive. – M. Eriksson Mar 18 '21 at 12:29

1 Answers1

1

The colors array has associative keys(eg. blue, etc...).

In order to access first element with $array['colors'][0],

need to convert array keys to numeric using array_values() function.

Either, access elements with associate keys like:

echo $array['colors']['blue'];
echo $array->colors['blue'];

Whichever best suits.

OR,

$colors = array_values($array['colors']);
echo $colors[0];
Pupil
  • 23,834
  • 6
  • 44
  • 66