Search notes:

PHP: associative arrays

An associative array allows to store key/value pairs.
<html>
<head><title>Associative Array</title></head>
<body>

<?php

$object = array ('one'   =>  1,
                 'two'   =>  2,
                 'three' =>  3);


foreach ($object as $key => $val) {
  print "<br>$key: $val";
}

?>

<p>See also <a href='array.html'>array.html</a> and <a href='array_key_exists.html'>array_key_exists.html</a>.

</body>
</html>
Github repository about-php, path: /associative_array.html

foreach

<!DOCTYPE html>
<html>
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>foreach</title>
</head>
<body>

   <?php 

      $a  = array ('one' => 1, 'two' => 2, 'three' => 3);

      foreach ($a as $key_ => $value_) {
        print "$key_ : $value_<br>";
      }
   
   ?>

</body>
</html>
Github repository about-php, path: /array/foreach.html

array_key_exists

array_key_exists($key, $ary) returns TRUE if the array $ary contains the key $key. Otherwise, it returns FALSE.
Note that counterintuitively , IMHO, the first parameter is the key and the second the array!
<!DOCTYPE html>
<html>
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>array_key_exists</title>
</head>
<body>

  <?php
      
    $dict = array ('one' =>  1, 'two' =>  2, 'three' =>  3);

    if (array_key_exists('one', $dict)) echo "key <i>one</i> exists<br>"; else echo "key <i>one</i> does not exist<br>";
    if (array_key_exists('foo', $dict)) echo "key <i>foo</i> exists<br>"; else echo "key <i>foo</i> does not exist<br>";

  ?>

</body>
</html>
Github repository about-php, path: /array/associative/key_exists.html
See also the function isset() which checks if a variable is declared and different from NULL.

See also

ksort($ary) sorts the elements in $ary according to the values of their keys.
array_is_list($ary) returns true if $ary is a sequential array and false if is an associative array.
Arrays
Other PHP snippets.

Index