#native_company# #native_desc#
#native_cta#

Create one array element with multiple indexes

By Ryan M Harris
on May 10, 2001

Idea:

Many may realize a limitation of arrays in PHP. You can only reference an element by a text index or an integer index. (i.e. $MyArray[0], $MyArray[“Hello”]). There is not an easy way of having an array element that has an integer index and a text index.

If you look closely at the PHP documentation, you will notice that PHP supports references. We can use this capability to virtualize support for multiple array indexes. Example code and output is given below.

Theoretically, making one array element reference another provides a virtualized support for multi index elements. See the PHP documentation for more information on the & operator.

Code:

<?PHP
   // Insert an element with "TextIndex" as the index
   $TestArray["TextIndex"]="This is a test element";
   // Insert an element with 0 as an integer index, but assign a reference to the above element
   $TestArray[0]=&$TestArray["TextIndex"];
   // Change the element with index 0
   $TestArray[0] = "Reset by second element";
   // The element with index "TestIndex" is also changed...
   print "Test :" . $TestArray["TextIndex"] . "n";
   // Show the array contents, let them know how this trick works...
   print_r($TestArray);
PHP?>

Output:

Test :Reset by second element
Array
(
[TextIndex] => Reset by second element
[0] => Reset by second element
)