RosettaCodeData/Task/Associative-array-Creation/PHP/associative-array-creation-1.php

22 lines
716 B
PHP
Raw Permalink Normal View History

2013-04-10 14:58:50 -07:00
$array = array();
2015-11-18 06:14:39 +00:00
$array = []; // Simpler form of array initialization
2013-04-10 14:58:50 -07:00
$array['foo'] = 'bar';
$array['bar'] = 'foo';
echo($array['foo']); // bar
echo($array['moo']); // Undefined index
2015-11-18 06:14:39 +00:00
// Alternative (inline) way
2013-04-10 14:58:50 -07:00
$array2 = array('fruit' => 'apple',
'price' => 12.96,
'colour' => 'green');
2015-11-18 06:14:39 +00:00
// Another alternative (simpler) way
$array2 = ['fruit' => 'apple',
'price' => 12.96,
'colour' => 'green'];
// Check if key exists in the associative array
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null