Artisan
Artisan

Reputation: 4112

How to display the key of key array in PHP?

This is the content of $records enter image description here

If I wanted to display the "key" of this key array, how to code?

e.g. in first round of foreach loop I like to display 1 (key), 1 (id), 10 (price) and so on. I would use $record['id'], $record['price'], but I don't know what to code to display the key?

Upvotes: 0

Views: 250

Answers (6)

Tim
Tim

Reputation: 99

<?php
foreach ($records as $record) {
    foreach ($record as $key => $value) {
        echo $value . '(' . $key . ')';
    }
}
?>

Upvotes: 1

Vikram
Vikram

Reputation: 3351

foreach($records as $key=>$record){
  echo "key: ".$key."</br>";
  echo "ID: ".$record['id']."</br>";
  echo "Price: ".$record['price']."</br>";
}

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

foreach($records as $key => $record) {
  echo $key . '(key), ' . $record['id'] . '(id), ' . $record['price'] . '(price)';
}

Upvotes: 2

Federico J.
Federico J.

Reputation: 15892

foreach ($records as $key => $record) {
    echo $key;
}

Check foreach in PHP manual for more info: http://php.net/manual/en/control-structures.foreach.php

Upvotes: 3

Maxime Lorant
Maxime Lorant

Reputation: 36161

Have you tried to use a foreach ?

foreach($records as $key => $value) {
     echo "Current key: ".$key."<br />";
     print_r($value);
}

Upvotes: 1

Janith Chinthana
Janith Chinthana

Reputation: 3844

foreach($records as $key=>$val){
   echo $key;
}

Upvotes: 2

Related Questions