12

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>
3
  • 2
    So, having ruled out the canonical and sensible approaches, what else did you try? Commented Dec 8, 2011 at 13:57
  • well i am confortable with foreach loop I just want to see if it is possible. Commented Dec 8, 2011 at 13:58
  • Why no foreach loops? Oh, you just answered as I posted! Commented Dec 8, 2011 at 14:00

5 Answers 5

34

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Parse error: syntax error, unexpected T_FUNCTION, expecting ')' in ... on line 183, gives an error but that's something cool :)
You must not be running PHP 5.3.0 :) - It's an easy fix, one sec I'll update my answer
Do you mean "Without PHP >= 5.3"?
The links are down.
7

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

2 Comments

...or because instead of using the named function "implode", he's used the alias "join", and hasn't formatted the answer in an easily readable way, or provided an explanation as to the limitations of the suggestion (PHP 5 >= 5.3). Implode is far more implicit when it comes to self-documentation.
I think that this answer is not quite right, using single instead of double quotes, and a backslash instead of forward slash, it should be: join("\n", array_map(function($a) { return "<a href=\"#$a\",>$a</a>";}, $links));
1

On modern PHP versions it could be shorten as follows.

$wrapper = static fn (string $link): string => \sprintf('<a href="#%1$s">%1$s</a>', $link);
$result = \array_map($wrapper, $links);

Comments

0

Reusable function.

function array_wrap_template($array, $template, $rep="{{el}}")
{
    return array_map(function($el)use($template, $rep){
        return str_replace($rep, $el, $template);
    }, array_values($array));
}

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

1 Comment

This answer is missing its educational explanation.
0

Another technique not yet mentioned is to use preg_replace() -- which will happily iterate an array of strings -- although, obviously this is not a task that actually demands a regex pattern. (Demo)

$links = array('london','new york','paris');
var_export(
    preg_replace('/.+/', '<a href="#$0">$0</a>', $links)
);

Otherwise, you can go that extra step toward generating encoded urls by calling urlencode() on the city string which is used as the href value.

var_export(
    array_map(
        fn($city) => sprintf('<a href="#%s">%s</a>', urlencode($city), $city),
        $links
    )
);

Comments

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.