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?
asked Mar 18, 2021 at 11:59
-
I suppose you named your variable $array?GlennM– GlennM2021年03月18日 12:01:56 +00:00Commented Mar 18, 2021 at 12:01
-
1$array['colors']['blue']Anurat Chapanond– Anurat Chapanond2021年03月18日 12:04:59 +00:00Commented Mar 18, 2021 at 12:04
-
Does this answer your question? How to get the first item from an associative PHP array?El_Vanja– El_Vanja2021年03月18日 12:12:42 +00:00Commented Mar 18, 2021 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.C3roe– C3roe2021年03月18日 12:26:27 +00:00Commented Mar 18, 2021 at 12:26
-
I would recommend reading through the manual page about arrays. It's pretty extensive.M. Eriksson– M. Eriksson2021年03月18日 12:29:28 +00:00Commented Mar 18, 2021 at 12:29
1 Answer 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];
answered Mar 18, 2021 at 12:02
lang-php