• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP Arrays / Working With Array Elements in PHP

Working With Array Elements in PHP

19 March 2010 / 2 Comments

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!

Filed Under: PHP Arrays Tagged With: access elements, adding elements, array_values, change elements, deleting elements, php arrays, print_r, read array values, removing elements, unset

Reader Interactions

Comments

  1. Jane Dumke says

    4 October 2021 at 6:06 pm

    How do you set an array element’s value to NULL?

    Reply
    • Matt Doyle says

      11 October 2021 at 3:30 am


      $element[index] = null;

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits