PHP Programming/Data Structures< PHP Programming
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.
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 StructuresEdit
- String is a structure to represent a singular value (aka scalar)
- Array is a structure to represent a list of values (aka vector)
$person_name = 'Alice';
$person_names = Array( 0=> 'Alice', 1=> 'Bob', 2=> 'Charlie', ); $alice_info = Array( 0=> 'Alice', 1=> 'Female', 2=> '26', 3=> 'firstname.lastname@example.org', );
PHP Composite StructuresEdit
- SimpleDictionary is a structure to represent an unordered sequence of name-value pairs. In native PHP, this is done using the standard Array with strings for indices.
- SimpleSequence is a structure to represent an ordered sequence of values. In native PHP, this is done using the standard Array with numeric indices.
- SimpleTable (aod) is an ordered sequence of one or more SimpleDictionary where each SimpleDictionary instance has matching names.
- SimpleTable (aoa) is a sequence of one or more SimpleSequence where each SimpleSequence instance has corresponding indices.
The square brackets method allows you to set up by directly setting the values. For example, to make $foobar = $foo, all you need to do is:
$person_names = Array( 'person1'=> 'Alice', 'person2'=> 'Bob', 'person3'=> 'Charlie', ); $alice_info = Array( 'first_name'=> 'Alice', 'sex'=> 'Female', 'age'=> '26', 'email'=> 'email@example.com', );
$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", ), ), );