Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Modifying Arrays

After you've created an array, what about modifying it? No problem—you can modify the values in arrays as easily as other variables. One way is to access an element in an array simply by referring to it by index. For example, say you have this array:

$fruits[1] = "pineapple";
$fruits[2] = "pomegranate";
$fruits[3] = "tangerine";

Now say you want to change the value of $fruits[2] to "watermelon". No problem at all:

$fruits[1] = "pineapple";
$fruits[2] = "pomegranate";
$fruits[3] = "tangerine";

$fruits[2] = "watermelon";

Then say you wanted to add a new element, "grapes", to the end of the array. You could do that by referring to $fruits[], which is PHP's shortcut for adding a new element:

$fruits[0] = "pineapple";
$fruits[1] = "pomegranate";
$fruits[2] = "tangerine";

$fruits[2] = "watermelon";

$fruits[] = "grapes";

All that's left is to loop over the array and display the array contents, as shown in Example 3-1, phparray.php.

Example 3-1. Modifying an array's contents, phparray.php

<HTML>
        <HEAD>
            <TITLE>
                Modifying an array
            </TITLE>
        </HEAD>

        <BODY>
            <H1>
                Modifying an array
            </H1>

        <?php
            $fruits[0] = "pineapple";
            $fruits[1] = "pomegranate";
            $fruits[2] = "tangerine";

            $fruits[2] = "watermelon";

            $fruits[] = "grapes";

            for ($index = 0; $index < count($fruits); $index++){
                
   echo $fruits[$index], "<BR>";            }
        ?>
    </BODY>
</HTML>

The results appear in Figure 3-1. As you can see, we not only were able to modify $fruits[2] successfully but were also able to add "grapes" to the end of the array.

03fig01.gif

Figure 3-1 Modifying an array.

You can also copy a whole array at once if you just assign it to another array:

<?php
    $fruits[0] = "pineapple";
    $fruits[1] = "pomegranate";
    $fruits[2] = "tangerine";
    $fruits[2] = "watermelon";
    $fruits[] = "grapes";
    $produce = $fruits;
    echo $produce[2];
?>

This script gives you this output:

watermelon
  • + Share This
  • 🔖 Save To Your Account