Iterating over unknown keys in php array (created with array_count_values)

69
March 06, 2018, at 10:46 AM

I have an array like this -

$fruit = Array ( [0] => bananas [1] => apples [2] => apples [3] => oranges [4] => oranges [5] => apples )

With which I have created a new array using array_count_values to count the individual fruits.

$fruitSorted = array_count_values($fruit)

Which looks like this:

Array ( [bananas] => 1 [oranges] => 2 [apples] => 3

So far I am happy. But I would like to iterate over the second array, but without knowing the names of the keys. Should it instead be a multi-dimensional array? I am not sure how to directly convert it. More directly, I would like to

foreach ($fruitSorted as $a){
    echo $a." is the value";
    //how to I select the key instead without knowing its name?
}

Thanks

Answer 1

Use $key => $value in the foreach() :

foreach ($fruitSorted as $key => $value){
   echo $key . " is the key, and " . $value . " is the value" ;
}
READ ALSO
how to use str_replace with array

how to use str_replace with array

I have this string:

88
General PHP good practices and coding style

General PHP good practices and coding style

I've been learning html and css, and now PHPIt is my first programming language and I would like to learn good practices and coding style to apply from now on, so I can extrapolate all that learning to a new language in the future (JavaScript, probably)

55
PHP/PDO Dynamically binding values (invalid param count error)

PHP/PDO Dynamically binding values (invalid param count error)

I was tasked (stuck) with trying to update an old mysql_query code to be PDO compliant

68