0

I have custom array in php:

$tags = [
    'portfolio',
    'material',
    'corporate'
];

How I can paste this array as javascript array in HTML element:

<div id="template" data-tags='["portfolio", "material", "corporate"]'></div>

I must do this task in php file and return to view.

I tired:

$result = "";
foreach ($tags as $tag) {
    $result .= '"'.$tag.'",';
}
$result = '<div class="getTags" style="display:none;" data-tags=\'['.$result.']\'></div>'; 
return $result;

But here data tags type not an array, it's string. How I can solve this problem?

6
  • Have you looked at json_encode() Commented Nov 14, 2018 at 14:21
  • Try to serialize array (you can use json_encode() function) and add it to client side. Commented Nov 14, 2018 at 14:22
  • You can create a JSON string from the array in PHP and parse it in JavaScript: [...document.querySelectorAll('.getTags')].map(el=>[el,JSON.parse(el.getAttribute('data-tags'))]) Commented Nov 14, 2018 at 14:22
  • @OlegNurutdinov Serializing is not the same as JSON-encoding Commented Nov 14, 2018 at 14:23
  • @PatrickQ thanks, of course, I make an error.) Commented Nov 14, 2018 at 14:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.