2

I need to append a prefix to each key in my array. The prefix it is defined outside the create_function I am using. How can I make it accessible from inside?

Here my code ($result is my array of key => value):

$groupName = $reader->getAttribute('name');

$resultKeyPrefixGroup = array_combine(
                    array_map(create_function('$k', 'return $groupName."/".$k;'), array_keys($result)),
                    $result
                );

Thank you!

user3563844
  • 113
  • 1
  • 8

2 Answers2

1

This hurt my brain wrapping my head around escaping the string:

<?php
$result = 
[
    '1' => 'One',
    '2' => 'Two'
];

$groupName = 'braves';

$resultKeyPrefixGroup = array_combine(
    array_map(
        create_function('$k', "return '$groupName/'.\$k;"),
        array_keys($result)
    ),
    $result
);
var_export($resultKeyPrefixGroup);

Output:

array (
    'braves/1' => 'One',
    'braves/2' => 'Two',
)

As create_function is deprecated as of 7.2.0 I'd recommend one of my alternative approaches.

Progrock
  • 7,373
  • 1
  • 19
  • 25
0

You could use an anonymous function:

<?php
$result = 
[
    '1' => 'One',
    '2' => 'Two'
];

$prefix = 'pink/';
$prefix_key = function($str) use ($prefix) {
    return $prefix . $str;
};

$prefixed = array_combine(
    array_map($prefix_key, array_keys($result)),
    $result
);

var_export($prefixed);

Output:

array (
  'pink/1' => 'One',
  'pink/2' => 'Two',
)

Though it might be just as well to loop and build your new array:

foreach($result as $k => $v)
    $prefixed["pink/$k"] = $v;
Progrock
  • 7,373
  • 1
  • 19
  • 25