sphinx9999 Posted January 25, 2008 Share Posted January 25, 2008 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? Quote Link to comment https://forums.phpfreaks.com/topic/87771-solved-perform-function-on-each-element-of-array/ Share on other sites More sharing options...
kenrbnsn Posted January 25, 2008 Share Posted January 25, 2008 Look at array_map() Ken Quote Link to comment https://forums.phpfreaks.com/topic/87771-solved-perform-function-on-each-element-of-array/#findComment-448958 Share on other sites More sharing options...
GingerRobot Posted January 25, 2008 Share Posted January 25, 2008 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); } ?> Quote Link to comment https://forums.phpfreaks.com/topic/87771-solved-perform-function-on-each-element-of-array/#findComment-448963 Share on other sites More sharing options...
sphinx9999 Posted January 28, 2008 Author Share Posted January 28, 2008 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. Quote Link to comment https://forums.phpfreaks.com/topic/87771-solved-perform-function-on-each-element-of-array/#findComment-451090 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.