/    Sign up×
Community /Pin to ProfileBookmark

lambda create function

curious as to how to create a quick lambda function
to take the keys of an already defined array and creating
a new array from them.

[code=php]
$type = ‘CHILD’;
$walk = array();
array_walk(create_function($data, ‘return “foreach ($data[$type] AS $k) $walk[$k endforeach;”‘));
print_r($walk);
[/code]

just trying to understand create_function and lambda, failing miserably at both i guess

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@ehimeauthorNov 29.2010 — should work the same as
[code=php]
$arr = array_keys($data[$type]);
[/code]
Copy linkTweet thisAlerts:
@NogDogNov 29.2010 — The function being used with array walk needs to accept two parameters (array key/index and the associated value). So the basic syntax for the create_function() part would be something like:
[code=php]
// use single quotes!
create_function('$key, $val', 'do_stuff_with($key) or do_stuff_with($val);')
[/code]

(In cases where you want to directly modify the array value, pass it by reference with the "&" operator.)

Now, whether array_walk is the way to go for what you are trying to do, I'm not sure, as I don't think I'm following exactly what you want to accomplish.
Copy linkTweet thisAlerts:
@ehimeauthorNov 29.2010 — Pretty much create a new array with the keys of the first as the

values of the second. Which is exactly what the previous post did.

I'm just trying to figure out how create_function works, atm I

can't see how it is necessary to anything I do, but I could always

use another tool in my kit.
Copy linkTweet thisAlerts:
@NogDogNov 30.2010 — The best I can think of to do within your restrictions (and why array_keys() will be much better ? ):
[code=php]
<?php
$array = range('a', 'd');
$keys = $array;
array_walk(
$keys,
create_function(
'&$value, $key',
'$value = $key;'
)
);
echo "<pre>".print_r($array,1)."</pre>";
echo "<pre>".print_r($keys,1)."</pre>";
[/code]
×

Success!

Help @ehime spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...