php add to associative array
snippet in php

Associative array in php

user4931

<?php 
/* 
There are 3 Types of array in php  
1. Indexed arrays - Arrays with a numeric index
2. Associative arrays - Arrays with named keys
3. Multidimensional arrays - Arrays containing one or more arrays

This is the second one - Associative arrays
*/

$age = array("Samy"=>"35", "Naveen"=>"37", "Amit"=>"43");
echo "Mr.Samy is " . $age['Samy'] . " years old.";

?>

php foreach associative array

user7260

<?php


$person_with_age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

//echo "Peter is " . $person_with_age['Peter'] . " years old."; //just one

//now loop
foreach($person_with_age as $person => $age) {
  echo "Key=" . $person . ", Value=" . $age;
  echo "<br>";
}


?>

php add to associative array

user1817

// for php 5.4+
$data += [$key => $value];

// for php 5.4-
$data += array($key => $value);

php add new item to associative array

user5200

$a = array('foo' => 'bar'); // when you create
$a['Title'] = 'blah'; // later