array_map not working

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nwp
Forum Contributor
Posts: 105
Joined: Sun Feb 04, 2007 12:25 pm

array_map not working

Post by nwp »

If string indexed array is given to array_map it returns numerically indexed array after applying the callback.See this code

Code: Select all

<?php
$r = array('one' => 'HeLlO', 'two' => 'Hi');
print_r($r);//Orgiginal array
$r = array_map('tst_it', $r, array(false));
function tst_it($r, $bool = false){
	if($bool){return strtoupper($r);}
	else{return strtolower($r);}
}
print_r($r);//Array after array_map
?>
But this is giving
Array
(
[one] => HeLlO
[two] => Hi
)
Array
(
[0] => hello
[1] => hi
)
See I've marked it bold.
Its numarically indexed instead of string indexed.
But how can I make it string index with the same key as original ??
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

nwp
Forum Contributor
Posts: 105
Joined: Sun Feb 04, 2007 12:25 pm

Post by nwp »

What type of answer is this ??
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

nwp wrote:What type of answer is this ??
A list of functions that may be of interest.
nwp
Forum Contributor
Posts: 105
Joined: Sun Feb 04, 2007 12:25 pm

Post by nwp »

But I wanna know why its giving such answer and how can I make it as I told above.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Your code was not engineered for array_map(). It was built for array_walk().
nwp
Forum Contributor
Posts: 105
Joined: Sun Feb 04, 2007 12:25 pm

Post by nwp »

Aha! Thanks for the tip.
Post Reply