[php] PHP: Get the key from an array in a foreach loop

print_r($samplearr) prints the following for my array containing 3 items:

Array ( [4722] => Array ( [value1] => 52 [value2] => 46 )
Array ( [4922] => Array ( [value1] => 22 [value2] => 47 )
Array ( [7522] => Array ( [value1] => 47 [value2] => 85 )

I want to put these into an HTML table so I was doing a foreach but its not doing what I expected:

foreach($samplearr as $item){
     print "<tr><td>" . key($item) . "</td><td>" . $samplearr['value1'] . "</td><td>" . $samplearr['value2'] . "</td></tr>";
}

Which is returning:

<tr><td>value1</td><td>52</td><td>46</td></tr>

This would be the first output I am wanting:

<tr><td>4722</td><td>52</td><td>46</td></tr>

What function do I need to be using instead of key($item) to get the 4722?

This question is related to php arrays foreach

The answer is


Use foreach with key and value.

Example:

foreach($samplearr as $key => $val) {
     print "<tr><td>" 
         . $key 
         . "</td><td>" 
         . $val['value1'] 
         . "</td><td>" 
         . $val['value2'] 
         . "</td></tr>";
}

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?