Certified PHP Developer Learning Resources Associative arrays

Learning Resources
 

Associative arrays


PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays.

Example - Mixed integer and string keys:


$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
);
var_dump($array);
?>

The above example will output:

array(4) {
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "foo"
  [100]=>
  int(-100)
  [-100]=>
  int(100)
}


To create an associative array


$car = array ("weight"=>"100kg", "year"=>"2004", "price"=>"7000");

?>
 

Alternative code:


$car["weight"] = "100kg";
$car["year"] = "2004";
$car["price"] = "7000";
$car["discount rebate"] = "12";

?>

To display the items in an array, do this:

// display car properties
print($car["price"]."
");

// display all car properties
foreach ($car as $property=>$value) {
print($property . " is " . $value . "
");
}

?>
 

To sort an associative array

asort() - Sorts an associative array by value. Returns nothing.
ksort() - Sorts an associative array by key. Returns nothing.

eg.


$fruittrolley = array ("apple"=>"100", "orange"=>"20", "pear"=>"30");

asort($fruittrolley);

print("After asort:
");

foreach ($fruittrolley as $fruit=>$no) {
print("There are $no ${fruit}s.
");
}

ksort($fruittrolley);

print("After ksort:
");

foreach ($fruittrolley as $fruit=>$no) {
print("There are $no ${fruit}s.
");
}

?>

prints:

After asort:
There are 20 oranges.
There are 30 pears.
There are 100 apples.

After ksort:
There are 100 apples.
There are 20 oranges.
There are 30 pears.

 For Support