Skip to content
Thomas Weinert edited this page Jul 12, 2018 · 3 revisions

FluentDOM\Query::map()

array map(callable $function);

Translate a set of elements in the FluentDOM\Query object into another set of values in an array (which may, or may not contain elements).

If the callback function returns an array each element of the array will be added to the result array. All other variable types are put directly into the result array.

Usage

$html = <<<HTML
<html>
  <head>
    <title>Examples: FluentDOM\Query::map()</title>
  </head>
  <body>
    <p><b>Values: </b></p>
    <form>
      <input type="text" name="name" value="John"/>
      <input type="text" name="password" value="password"/>
      <input type="text" name="url" value="http://ejohn.org/"/>
    </form>
  </body>
</html>
HTML;

$fdQuery = FluentDOM($html);
echo $fdQuery
  ->find('//p')
  ->append(
    implode(
      ', ',
      $fdQuery
        ->find('//input')
        ->map(
          function($node, $index) {
            return FluentDOM($node)->attr('value');
          }
        )
    )
  );

Output

<?xml version="1.0"?>
<html>
  <head>
    <title>Examples: FluentDOM\Query::map()</title>
  </head>
  <body>
    <p><b>Values: </b>John, password, http://ejohn.org/</p>
    <form>
      <input type="text" name="name" value="John"/>
      <input type="text" name="password" value="password"/>
      <input type="text" name="url" value="http://ejohn.org/"/>
    </form>
  </body>
</html>
Clone this wiki locally