php - array_walk vs array_map vs foreach

314

I'm trying to compare these three but it seems onlyarray_map works.

$input = array( '  hello   ','whsdf                                    ','                              lve you','                              ');
$input2 = array( '  hello   ','whsdf                                    ','                              lve you','                              ');
$input3 = array( '  hello   ','whsdf                                    ','                              lve you','                              ');

$time_start = microtime(true);
$input = array_map('trim',$input);
$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did array_map in $time seconds<br>";

foreach($input as $in){
    echo "'$in': ".strlen($in)."<br>";
}

////////////////////////////////////////////////

$time_start = microtime(true);
array_walk($input2,'trim');
$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did array_walk in $time seconds<br>";

foreach($input2 as $in){
    echo "'$in': ".strlen($in)."<br>";
}

////////////////////////////////////////////////


$time_start = microtime(true);
foreach($input3 as $in){
    $in = trim($in);
}
$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did foreach in $time seconds<br>";

foreach($input3 as $in){
    echo "'$in': ".strlen($in)."<br>";
}

What Am I Doing Wrong? Here's the output:

Did array_map in 0.00018000602722168 seconds
'hello': 5
'whsdf': 5
'lve you': 7
'': 0
Did array_walk in 0.00014209747314453 seconds
' hello ': 10
'whsdf ': 41
' lve you': 37
' ': 30
Did foreach in 0.00012993812561035 seconds
' hello ': 10
'whsdf ': 41
' lve you': 37
' ': 30

It's not trimming forarray_walk and theforeach loop.

627

Answer

Solution:

As of PHP 5.3 Anonymous Functions possible. ex:

$arr = array('1<br/>','<a href="#">2</a>','<p>3</p>','<span>4</span>','<div>5</div>');
array_walk($arr, function(&$arg){
    $arg = strip_tags($arg);
});
var_dump($arr); // 1,2,3,4,5 ;-)

Have fun.

People are also looking for solutions to the problem: Access multidimensional array keys with on-the-fly generated variables with php (need to avoid eval)

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.