Jump to content

[SOLVED] Perform function on each element of array


sphinx9999

Recommended Posts

Hi,

 

Is there any way of performing a function on each element of an array without (manually) going through a loop? For example I need to convert all elements to integers. This could be done by:

$arr=array('3',4,'6','34.4','tr');
$temparr=array();
foreach($arr as $a){
$temparr[]=intval($a);
}

Ideally I want to use a callback function as in array_walk. However, although this removes the need for the loop it will not change the actual array so I will still need the temporary array. I know a for loop will allow me to change the elements directly but it still loops...

 

Any thoughts?

You can also use array_walk if you pass by reference (see the function test_alter in example one here) and you can use a foreach loop like this:

 

<?php
$arr=array('3',4,'6','34.4','tr');
foreach($arr as $k => $v){
    $arr[$k] = intval($v);
}
?>

Look at array_map()

 

Ken

Excellent solution - was hoping there would be a simple function to perform this. It even works with a built-in function:

$arr=array_map('intval',$arr);

Thanks

 


 

You can also use array_walk if you pass by reference (see the function test_alter in example one here) and you can use a foreach loop like this:

 

<?php
$arr=array('3',4,'6','34.4','tr');
foreach($arr as $k => $v){
    $arr[$k] = intval($v);
}
?>

Thanks too - I hadn't any idea that an array could be manipulated directly in a foreach like that (even though it makes complete sense looking back...). Will certainly use this in future.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.