Top Ad unit 728 × 90

ticker

Associative Arrays In PHP | Array Example In PHP

Associative Arrays In PHP | Array Example In PHP



So far, you have been accessing the values of an array using integers. This is all well and good, but if you want to be more descriptive of your data, you can make use of something called an associative array.



An associative array makes use of (key => value) pairs. Some languages may separate arrays from associative arrays, but PHP treats both as the same.



In the editor, you will see I have declared two variables as arrays. Have a look at the first array and see if you can guess what item those values may refer to?



Now have a look at the array below it. This is an associative array. It's defined as an array like the first one, but see how I have specified keys for each of the values?



Both arrays contain the same values, but in the associative array, we can access the value using a specified "key".








<html>
  <head>
    <title>Making the Connection</title>
  </head>
  <body>
    <p>
      <?php
        // This is an array using integers as the indices.
        // Add 'BMW' as the last element in the array!
        $car = array(2012, 'blue', 5 ,'BMW');

        // This is an associative array.
        // Add the make => 'BMW' key/value pair!
        $assocCar = array('year' => 2012,'make'=>'BMW',
                   'colour' => 'blue',
                   'doors' => 5);
            
        // This code should output "BMW"...
        echo $car[3];
        echo '<br />';
            
        // ...and so should this!
        echo $assocCar['make'];
      ?>
    </p>
  </body>
</html>
Associative Arrays In PHP | Array Example In PHP Reviewed by Rajat Jha on 23:18:00 Rating: 5

No comments:

All Rights Reserved by INFO PHP 99 © 2014 - 2015
Powered by Blogger, Designed by Sweetheme

Contact Form

Name

Email *

Message *

Powered by Blogger.