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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.