<?php $my_ar[] = "Hello"; $my_ar[] = "Mrs."; $my_ar[] = "Robinson"; ?> TechniqueYou 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"); ?> CommentsUsing 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. |