Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array element wrap all elements

Tags:

arrays

php

I would like to wrap all elements of an array with something like but i don't want a lot of lines or foreach loop

$links = array('london','new york','paris');

// the outcome should be 

<a href="#london">london</a>
<a href="#new york">new york</a>
<a href="#paris">paris</a>
like image 449
Val Avatar asked Dec 08 '11 13:12

Val


2 Answers

How about array_map?

$links   = array('london', 'new york', 'paris');
$wrapped = array_map(
   function ($el) {
      return "<a href=\"#{$el}\">{$el}</a>";
   },
   $links
);

Demo (Click source)

Without PHP > 5.3, you can't use a lambda function, so you'll need something like this:

function wrap_those_links($el)  { 
      return "<a href=\"#{$el}\">{$el}</a>"; 
}

$links   = array('london', 'new york', 'paris');
$wrapped = array_map('wrap_those_links', $links);

Demo for PHP 5.2 (Again, click Source)

like image 170
nickb Avatar answered Oct 01 '22 06:10

nickb


Try join('\n', array_map(function($a) { return "<a href=\"#$a\",>$a<\\a>";}, $links));

like image 42
Ed Heal Avatar answered Oct 01 '22 07:10

Ed Heal