Saturday, April 28, 2012

Is it possible to pass array keys by reference using PHP's native foreach control structure?

Answer: No. However, you can have by ref access to an array's keys using the following code:
<?php
ArrayUtil::ForEachFn($array, function (&$key, &$value) {
    // YOUR CODE HERE
});
To use this technique in your project simply add the following class:
<?php
class ArrayUtil
{
    public static function ForEachFn(Array &$array, $fn)
    {
        $newArray = array();
        foreach ($array as $key => $value)
        {
            $fn($key, $value);
            $newArray[$key] = $value;
        }
        $array = $newArray;
    }
}
To see it all in action checkout the following example:
<?php
// EXAMPLE ARRAY
$array = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
);

// BEFORE
print_r($array);

// EXAMPLE USAGE
ArrayUtil::ForEachFn($array, function (&$key, &$value) { // NOTE THE FUNCTION'S SIGNATURE (USING & FOR BOTH $key AND $value)
    if ($key === 'key2')
    {
        $key = 'BY REF KEY EXAMPLE'; // THIS IS THE WHOLE POINT OF THIS POST
    }
    if ($value === 'value2')
    {
        $value = 'BY REF VALUE EXAMPLE';
    }
});

// AFTER
print_r($array);

/* THE ABOVE "EXAMPLE USAGE" OUTPUTS:
Array
(
    [key1] => value1
    [key2] => value2
    [key3] => value3
)
Array
(
    [key1] => value1
    [BY REF KEY EXAMPLE] => BY REF VALUE EXAMPLE
    [key3] => value3
)
*/

Looking for a cloud-based catalog and CRM platform? Checkout http://rocware.com/

4 comments:

About Me

My photo
I code. I figured I should start a blog that keeps track of the many questions and answers that are asked and answered along the way. The name of my blog is "One Q, One A". The name describes the format. When searching for an answer to a problem, I typically have to visit more than one site to get enough information to solve the issue at hand. I always end up on stackoverflow.com, quora.com, random blogs, etc before the answer is obtained. In my blog, each post will consist of one question and one answer. All the noise encountered along the way will be omitted.