Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - Understanding PHP Arrays and Their Basic Operations

By: FYICenter.com

Part:   1  2   3  4 

(Continued from previous part...)

How To Retrieve Values out of an Array?

You can retrieve values out of arrays using the array element expression $array[$key]. Here is a PHP example script:

<?php $languages = array(); $languages["Zero"] = "PHP"; $languages["One"] = "Perl"; $languages["Two"] = "Java"; print("Array with inserted values:\n"); print_r($languages); ?>

This script will print:

Array with default keys:
The second value: Perl

Array with specified keys:
The third value: Java

What Types of Data Can Be Used as Array Keys?

Two types of data can be used as array keys: string and integer. When a string is used as a key and the string represent an integer, PHP will convert the string into a integer and use it as the key. Here is a PHP script on different types of keys:

<?php 
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
print("Array with mixed keys:\n");
print_r($mixed);
print("\$mixed[3] = ".$mixed[3]."\n");
print("\$mixed[\"3\"] = ".$mixed["3"]."\n");
print("\$mixed[\"\"] = ".$mixed[""]."\n");
?>

This script will print:

Array with mixed keys:
Array
(
    [Zero] => PHP
    [1] => Perl
    [Two] => Java
    [3] => C+
    [] => Basic
)
$mixed[3] = C+
$mixed["3"] = C+
$mixed[""] = Basic

Note that an empty string can also be used as a key.

How Values in Arrays Are Indexed?

Values in an array are all indexed their corresponding keys. Because we can use either an integer or a string as a key in an array, we can divide arrays into 3 categories:

  • Numerical Array - All keys are sequential integers.
  • Associative Array - All keys are strings.
  • Mixed Array - Some keys are integers, some keys are strings.

Can You Add Values to an Array without a Key?

Can You Add Values to an Array with a Key? The answer is yes and no. The answer is yes, because you can add values without specifying any keys. The answer is no, because PHP will add a default integer key for you if you are not specifying a key. PHP follows these rules to assign you the default keys:

  • Assign 0 as the default key, if there is no integer key exists in the array.
  • Assign the highest integer key plus 1 as the default key, if there are integer keys exist in the array.

Here is a PHP example script:

<?php 
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
print("Array with default keys:\n");
print_r($mixed);
?>

This script will print:

Array with default keys:
Array
(
    [Zero] => PHP
    [1] => Perl
    [Two] => Java
    [3] => C+
    [] => Basic
    [4] => Pascal
    [5] => FORTRAN
)

(Continued on next part...)

Part:   1  2   3  4 


Selected Developer Jobs:

More...