April 9, 2012

set key and values on array

Question by user983248

I have on array like:
$myarray = array("color", "red", "size", "big", "flavor", "bitter"); where color, size and flavor are the keys and the other are the values. How can I loop true the values only on the array.

I have a few arrays like that one so I only need to create a table and display their values like:

       // I'm stuck here because I don't know how to get the values of each array

Any help will be appreciated

Answer by deceze

while (list(, $key) = each($array)) {
    $value = current($array);

    echo $key, ': ', $value, PHP_EOL;

But yes, you should really use a proper associative array instead of this makeshift solution.

Answer by Starx

You are defining array incorrectly.


Then use it with foreach

foreach($myarray as $key => $value) {
   echo $key; //echoes the indexes like color
   echo $value; //echoes values like red

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!