The PHP Array Function

The PHP Array Function
It is very easy to create a new array using the PHP array( ) function. A PHP array is a special type of variable that stores and organizes data. What makes an array variable special is that it can store more than one value; in fact, you can store as many values in one array as you need. But how can this array keep all those values organized? It uses index positions assigned to each value. You can think of an array as a stack of library books. The name of the array variable would be $books and the index positions ([0], [1], [2]) would be the unique number given to each book in the library and the title of the books would be the values in the array. Notice in the example below that the index positions begin with a zero and not with a one.

$books[0] = "Gone With The Wind";
$books[1] = "Little Women";
$books[2] = "War And Peach";

It is very easy to create a new array and populate that array with more than one value or element by using the PHP array( ) function. As you can see below, the name of the array variable is followed by an equal sign and then the function name. On the right of the function name are the values in the array placed between parentheses. Each value is separated by a comma and enclosed within quotation marks. The whole thing ends with a semicolon.

$variable_name = function_name("value", "value",
"value");

$books = array("Gone With The Wind",
"Little Women", "War And Peach");
Note--The arrow indicates that the code is wrapped to a second line and should really be all on one line.

  1. The two examples above are really the same array written two different ways.

  2. You can add a value to an existing array by using the array operator [ ]. For example, we can add a new book to our $books array.

    $books[ ] = "Crime and Punishment";


  3. You can also use the array operator [ ] to start a new array that has only one variable.

    $names[ ] = "Diane Cipollo";





This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.