Home > Articles

chap3_0672323257

  • Print
  • + Share This

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.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.