Home > OS >  How to add html tag in each array elements in php?
How to add html tag in each array elements in php?

Time:03-17

I want to add an html element to each array element and render in dataTable as single string with each element as clickable object:

array:12 [▼
  0 => "00218"
  1 => "00332"
  2 => "00602"
  3 => "00701"
  4 => "00783"
  5 => "00806"
]

consider above array and want to add <a> in all array elements. example:

array:12 [▼
  0 => "<a href="/show/">00218"
  1 => "<a href="/show/">00332"    
]

will render as 00218 00332 each element as clickable.

CodePudding user response:

So you have an array like below

$array = array(
  0 => "00218",
  1 => "00332",
  2 => "00602",
  3 => "00701",
  4 => "00783",
  5 => "00806"
);

And you want to replace numbers with strings of anchor tags. A way of doing that is like below

for ($i = 0; $i < count($array); $i  ) {
    $array[$i] = '<a href="/show/' . $array[$i] . '">' .  $array[$i] . '</a>';
}

CodePudding user response:

<?php

function addLink($item)
{
    return ("<a href='/show/" . $item . "'>" . $item . "</a>");
}

$a = [1, 2, 3, 4, 5];
$b = array_map('addLink', $a);

var_dump($b);

https://www.php.net/manual/en/function.array-map.php

  • Related