Add new key value pair to associative array in PHP

Description

The following code shows how to add new key value pair to associative array.

Example


//from  w w w  .  j av a  2  s.c  o m
<!DOCTYPE html>
<html>
  <body>
    <h1>Adding Author Names</h1>
    <?php
    $authors = array( "A", "B", "C", "D", "E", "F" );
    
    $books = array(
      array(
        "title" => "A Book",
        "authorId" => 2,
        "pubYear" => 1937
      ),
      array(
        "title" => "B Book",
        "authorId" => 0,
        "pubYear" => 1939
      ),
      array(
        "title" => "C Book",
        "authorId" => 3,
        "pubYear" => 1859
      ),
      array(
        "title" => "D Book",
        "authorId" => 4,
        "pubYear" => 1667
      ),
      array(
        "title" => "E Book",
        "authorId" => 5,
        "pubYear" => 1945
      ),
      array(
        "title" => "F Book",
        "authorId" => 1,
        "pubYear" => 1925
      ),
    );
    
    foreach ( $books as &$book ) {
      $book["authorName"] = $authors[$book["authorId"]];
    }
    
    echo "<pre>";
    print_r( $books );
    echo "</pre>";
    
    ?>

  </body>
</html>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone