User login

Use array_map() to apply a function to every element of an array

Say you have an array that's just a little messy and you need to apply a function to every value in that array... you probably want http://us2.php.net/array_map and not http://us.php.net/array_walk

To do this:

<?php
  $fixed = array();
  foreach ($predicates as $predicate) {
    $fixed[] = trim($predicate);
  }
  $predicates = $fixed;
?>

<?php
  $predicates = array_map('trim', $predicates);
?>

No good: array_walk($predicates, 'trim');

as evidenced by

<?php
  drupal_set_message('<pre>'.var_export($predicates,TRUE).'</pre>'); 
?>

array (
0 => 'this:will',
1 => 'work:now',
2 => 'is:not',
3 => 'that:great',
4 => 'so:close',
5 => 'this:works',
6 => 'cleaner:now',
)

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.