- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
3.1 Declaring an Array
You want to specify a list for your program instead of sequentially adding items to your array:
<?php $my_ar[] = "Hello"; $my_ar[] = "Mrs."; $my_ar[] = "Robinson"; ?>
Technique
You can graduate from this basic method of specifying lists to array constructs, which enables you to easily specify lists in your program:
<?php $my_ar = array("Hello", "Mrs.", "Robinson"); ?>
Comments
Using the array() construct to specify an array instead of manually adding items to an array was one of Rasmus Lerdorf's (the creator of PHP) top-ten signs of an experienced PHP programmer. The array() construct makes it much easier for programmers to quickly specify lists.
If you have a large array, it is usually better to store your array in a file and retrieve the array when you load your program:
<?php function load_data ($name) { $data = implode ("", file ('${name}_var')); $var = unserialize ($data); return ($var); } function save_data ($name, $var) { $fp = @fopen ("${name}_var", "w") or die ("Cannot open ${name}_var for write access"); fwrite ($fp, serialize ($var)); @fclose ($fp); } $friends = load_data('friends'); $friends[] = 'Tim'; save_data ('friends', $friends); ?>
In the code, we use the serialize() function, which returns the string representation of a variable, and write that string to a file. In the load_data() function, we read the file containing the string representation of our variable into the $data variable by using a combination of implode() and file(). After we have this data, we use the unserialize() function to convert the data back into the original variable, which we return from the function.