Working With Array Elements in PHP

How to read and change PHP array values, how to add and remove array elements, and how to display an entire array.

In Creating Arrays in PHP, you learned how PHP arrays work, and saw how to create an array using PHP.

In this article you take things further, and look at how to access the individual elements inside a PHP array. You'll see how to:

  • Read element values
  • Alter element values
  • Add and remove elements in an array
  • Output the entire contents of an array

Reading array elements

To access an element within an array, you write the array's variable name, followed by the index of the element in square brackets:


$myArray[index]

The following example displays the value of the 3rd element in an array (remember that array indices start from zero):


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Martin Scorsese"
echo $directors[2];

Associative arrays work in the same way, except that you use a string index instead of a numeric one:


$movie = array( "title" => "Rear Window",
                "director" => "Alfred Hitchcock",
                "year" => 1954 );

// Displays "Rear Window"
echo $movie["title"];

Changing element values

You assign a new value to an array element in the same way as a regular variable:


$myArray[index] = new value;
The following example changes the 3rd element of the array from "Martin Scorsese" to "Woody Allen":


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
$directors[2] = "Woody Allen";

Adding elements

You can add a new element to an array like this:


$myArray[] = value;

PHP automatically assigns the next available numeric index to the new element. Here's an example:


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
$directors[] = "Woody Allen";

// Displays "Woody Allen"
echo $directors[4];

You can also specify an index. If an element with that index already exists in the array, its value is overwritten; otherwise a new element is created with that index:


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
$directors[4] = "Woody Allen";

// Displays "Woody Allen"
echo $directors[4];

$directors[2] = "Ingmar Bergman";

// Displays "Ingmar Bergman"
echo $directors[2];

Removing elements

To remove an element from an array, you call unset(), passing in the element to remove. (You can also use unset() on regular variables to delete them.) Here's an example:


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Stanley Kubrick"
echo $directors[1];

unset( $directors[1] );

// Displays nothing (and generates an "Undefined offset" notice)
echo $directors[1];

The last line of code above generates an "Undefined offset" notice, which is a minor error. It means that you're trying to access an array index that doesn't exist. Normally, PHP doesn't display or log notices, but you can change this with the error_reporting() function.

unset() doesn't automatically reindex arrays to "close the gap" in the index numbering. For example, after running the above code, "Martin Scorsese" still has an index of 2, and "Fritz Lang" still has an index of 3. To reindex the array so that the indices are contiguous again, you can use the array_values() function. For example:


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Stanley Kubrick"
echo $directors[1] . "<br />";

unset( $directors[1] );
$directors = array_values( $directors );

// Displays "Martin Scorsese"
echo $directors[1] . "<br />";

Outputting an array with print_r()

Sometimes when debugging your code it's useful to inspect the entire contents of an array. However, using print() or echo() on an array isn't much help:


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Array"
echo $directors;

To display an entire array, use the print_r() function instead. Here's an example that creates an indexed array and an associative array, then displays the contents of both arrays using print_r():


$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

$movie = array( "title" => "Rear Window",
                "director" => "Alfred Hitchcock",
                "year" => 1954 );

echo '<h2>$directors:</h2><pre>';
print_r( $directors );
echo '</pre><h2>$movie:</h2><pre>';
print_r( $movie );
echo "</pre>";

The above code produces the following output:


$directors:

Array
(
    [0] => Alfred Hitchcock
    [1] => Stanley Kubrick
    [2] => Martin Scorsese
    [3] => Fritz Lang
)

$movie:

Array
(
    [title] => Rear Window
    [director] => Alfred Hitchcock
    [year] => 1954
)

To return the output from print_r() as a string instead of displaying it, pass a second argument with a value of true to print_r().

Summary

In this article you've seen how to manipulate array elements in PHP. You've learned how to:

  • Read and change element values
  • Add and remove elements (including how to reindex indexed arrays), and
  • Display the entire contents of an array.

In future articles I'll be showing you how to work with multiple array elements at once, how to count the elements in an array, how to loop through arrays, and much more. Happy coding!

Learn PHP With Ease!

Written by Matt Doyle — ELATED's resident Web programming expert — Beginning PHP 5.3 is a complete introduction to PHP, covering everything in these tutorials and lots more besides. Find out how to:

  • Set up PHP on your computer
  • Use strings, arrays, functions and objects
  • Create interactive Web forms
  • Handle cookies and sessions
  • Work with files on the server
  • Build database-driven sites with MySQL
  • Send emails from your scripts
  • Create images on the fly with PHP
  • Work with regular expressions
  • Write robust, secure PHP applications

...and lots more!

“What a pleasure it's been spending hours and hours studying PHP with this magical book.” — Lulio, Florida
“The book is not only great for learning, but I find myself using it constantly as a reference as well!” — David A. Stoltz

Buy Beginning PHP 5.3 now from Amazon.comBeginning PHP 5.3 or Amazon.co.ukBeginning PHP 5.3.

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page