Defining Arrays in PHP

The simplest was to define an array variable is the array() function. Here's how:

<?php
// define an array
$position = array('first', 'second', 'third');
?>

The rules for choosing an array variable name are the same as those for any other PHP variable: it must begin with a letter or underscore, and can optionally be followed by more letters, numbers and underscores.
Alternatively, you can define an array by specifying values for each element in the index notation, like this:

<?php
// this is the same as the previous array
$position[0] = 'first';
$position[1] = 'second';
$position[2] = 'third';
?>

If you're someone who prefers to use keys rather than default numeric indices, you might prefer the following example:

<?php
// define an array
$numbers['one'] = 1;
$numbers['two'] = 2;
$numbers['three'] = 3;

// or is can also be defined as
$numbers = array('one' => 1, 'two' => 2, 'three' => 3);
?>

You can add elements to the array in a similar manner. For example, if you wanted to add the element 'four' to the $numbers array, you would use something like this:

<?php
// add an element to an array
$numbers['four'] = 4;
?>

In order to modify an element of an array, simply assign a new value to the corresponding scalar variable. If you wanted to replace 'third' with 'last', you'd use:

<?php
// modify an array
$position[2] = 'last';
?>

You can do the same using keys. The following statement modifies the element with the key 'three' to a different value:

<?php
// modify an array
$numbers['three'] = 4;
?>

Read more

About This Blog

This is a place where I write about the things I find interesting and are worth to share.