11

I want to know how to pass more arguments to my array_walk..

$addresses = array('www.google.com', 'www.yahoo.com', 'www.microsoft.com');
$a = 'hey';
$b = 'hey';
array_walk($addresses, array($this, '_handle'), $a, $b); // $a and $b parameters doesn't get passed

private function _handle($address,$a, $b) {
       echo $address; // www.google.com
       echo $a // 012
       echo $b // 012
}

How do I pass parameters anyway? I have to pass more than 5 parameters.. please teach me.. thanks!

0

4 Answers 4

21

The third parameter is a mixed data type. If you have many parameters, I would suggest putting them into an Array - perhaps an associative array to name them. You'd then pull them back out of that param:

$addresses = array('www.google.com', 'www.yahoo.com', 'www.microsoft.com');
$params = array('first','second');
array_walk($addresses, array($this, '_handle'), $params);

private function _handle($address,$count, $params) {
       echo $address; // www.google.com
       echo $params[0]; // first
       echo $params[1]; // second
}
Sign up to request clarification or add additional context in comments.

2 Comments

ohh ok.. sorry i don't understand the php manual. it says userdata and i don't have any idea that it's an array.. thanks man
@Kevin: userdata can be an array, it can be whatever you want. It can be an int, a string, an object, an array, etc. An array is used so you can have multiple values.
5

It will only allow one argument for user data. I suggest passing your values as an array.

array_walk($addresses, array($this, '_handle'), array($a, $b));

Comments

5

The function passed to array_walk() takes 2-3 parameters.

  1. Array Value (as a reference, if needed)
  2. Array Key
  3. Custom data (optional)

To pass multiple variables to array_walk pass an array.

array_walk($addresses, array($this, '_handle'), array('a'=>$a, 'b'=>$b));

private function _handle($address, $k, $data){
  echo $address;
  echo $data['a'];
  echo $data['b'];
}

Comments

4

You can use the use keyword with an anonymous function like this:

Note: $custom_var is a mixed datatype so can be an array if you want to pass several values

$custom_var = 'something';

array_walk( 
      $array, 
      function( &$value, $key) use ( $custom_var ){ 
    
      // Your code here, you can access the value of $custom_var
    
      });

2 Comments

Thank you, this is what i was looking for, but ill edit your answer to make it a bit clearer
@UriahsVictor thank you so much .

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.