PHP Programming/Data Structures

< PHP Programming

Variable variables

PHP has a legacy concept called "variable variables". This is an older, more limited programming concept that came before composite data structures were available. Since the PHP language now supports composite data structures, the concept of variable variables is essentially obsolete.

The PHP manual states:

   "Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically."

This approach has historically been used in programming languages that do not support composite data structures. There is no programmatic function or algorithm in PHP that can be obtained with variable that cannot also be obtained with composite data structures.

Moreover, "variable variables" are error-prone and require more maintenance overhead.

The Basics

Data structures are the way to represent composite entities using regular PHP variables.

Those familiar with database design and database implementation know about the concept of database normalization.

Data structures in PHP represent a similar concept. Whenever dealing with complex concepts and representing them in PHP, data structures are a way to normalize PHP variables to consistently and uniformly represent complex concepts.

PHP Native Structures

Examples

String Example:

 $person_name = 'Alice';

Array Examples:

 $person_names = Array( 0=> 'Alice', 1=> 'Bob', 2=> 'Charlie',  );
 $alice_info   = Array( 0=> 'Alice', 1=> 'Female', 2=> '26', 3=> 'alice@example.com',  );

PHP Composite Structures

The square brackets method allows you to set up by directly setting the values. For example, to make $foobar[1] = $foo, all you need to do is:

Examples

SimpleDictionary Examples:

 $person_names = Array( 'person1'=> 'Alice', 'person2'=> 'Bob', 'person3'=> 'Charlie',  );
 $alice_info   = Array( 'first_name'=> 'Alice', 'sex'=> 'Female', 'age'=> '26', 'email'=> 'alice@example.com',  );

SimpleDictionary Examples:

$user_profile = Array(
  main => Array(
    first_name  => "Archibald",
    last_name   => "Shaw",
    sex         => "male",
    age         => "33",    
  ),
  guardian => Array(
    first_name => "",
    last_name => "",
  ),
  children => Array(
    0 => Array(
      first_name => "Sally",
      last_name => "Shaw",
    ),
    1 => Array(
      first_name => "Scott",
      last_name => "Shaw",
    ),
  ),
  
);

Notes and references

[1]

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.