Skip navigation

If you don’t understand what the title is saying, I am talking about accessing the actual text name of a key in an array from within that same array during the initialization of that array in PHP. In essence, I want to have this:

<?php
$array = array('testing' => 'This is the value of the array index [<key name>].');
echo ($array['testing']);
?>

echo out the following:

This is the value of the array index [testing].

Well, I found out that this is entirely possible, and actually isn’t very difficult. To do this in PHP, you simply have to do this:

<?php
$array = array(($keyname = 'testing') => 'This is the value of the array index ['.$keyname.'].');
echo ($array['testing']);
?>

This code will work, and will output the following:

This is the value of the array index [testing].

That’s all there is to it! This will work with multidimensional arrays as well as simple one dimension arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>