Skip to content

Instantly share code, notes, and snippets.

@proclnas
Created September 6, 2017 13:38
Show Gist options
  • Save proclnas/71b52c0c7f2e51cd926b617caca11982 to your computer and use it in GitHub Desktop.
Save proclnas/71b52c0c7f2e51cd926b617caca11982 to your computer and use it in GitHub Desktop.
<?php
/**
* Monta string à partir de um array de chave/valor
*/
// rodrigo@blue-wind[~/repositorios/php] $ php reduce.php
// <a href="http://google.com" id="java" class="php"/>
$a = [
'href' => 'http://google.com',
'id' => 'java',
'class' => 'php'
];
$initialPiece = '<a';
$finalPiece = '/>';
$keys = array_keys($a);
$counter = 0;
$element = array_reduce($a, function($final, $atual) use (&$counter, $keys) {
$final .= sprintf(' %s="%s"', $keys[$counter], $atual);
$counter++;
return $final;
}, $initialPiece);
$element .= $finalPiece;
echo $element . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment