1

I'm trying to apply a function for each array but it doesnt work, here's my code:

$array['a'] = "aaa";
$array['b'] = "bbb";

function myFunction ($array) {
   ## some code
   };

foreach ($array as $value) {
   echo myFunction($array[$value]);
   };

Thx for your help.

3 Answers 3

4

karthikr is correct. you can also use a shorthand function instead of your foreach loop:

array_walk($array, 'myFunction');

see http://www.php.net/manual/en/function.array-walk.php

Sign up to request clarification or add additional context in comments.

Comments

3

try this:

$array['a'] = "aaa";
$array['b'] = "bbb";

function myFunction ($array) {
   ## some code
   };

foreach ($array as $key => $value){
   echo myFunction( $value );
};

Comments

2

As for your title, if you need to apply a callback function to every (more than 1) array, let's use array_map():

$func = function($value) {  
  return $value * 2;  
};

print_r(array_map($func, range(1, 5)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.