Implicit Evaluation with PHP

1 May 2006

Accessing Multi-dimensional Array

This weekend, I got an email from a reader wondering how to access non-constant indices of a multidimensional array.

Given an HTML field like <input name=”users[username][email]” type=”text” />

He needed to know how to access it. After trying multiple things, the solution he found was:
$property = "[username][email]";
$field = $_POST["users"];
$result = eval ("$field$property;");

The more obvious $result = $field[$property]; of course fails to work, because the square brackets in the property variable are treated as a string in the array key name rather than an array delimiter.

The solution, in a static sense, is to use multiple delimiters.
$field["[username][email]"]; // does not work
$field["username"]["email"]; // does work

The twist in this readers question was that each index was variable. While this seems unnecessarily complex to me, there may well be a valid reason behind it.

function getSubArray ($array) {
$results = (array)NULL;
if (is_array ($array)) {
foreach ($array as $key => $value) {
$results[$key] = getSubArray ($value);
}
} else {
$results[] = $array;
}
return $results;
}
$results = getSubArray($_POST); // example
$results = getSubArray($_POST["users"]); //example

I don’t see that its particulary useful. In fact, untested, that seems identical to $results = $_POST; But by providing the transversal code, hopefully it can be adopted to whatever need you have.

No Comments currently posted.

Post a comment on this entry: