-1

I'm filling an input type hidden field with an array of values from PHP:

        foreach ($categorie as $cat) {
        $elenco_categorie .= $cat['nome'].", ";
    }
    echo '<input type="hidden" name="elenco_cat" value="'.$elenco_categorie.'">';

and after that i am printing the field which will contain the list of all my categories, separated by ", ". I don't know how to fill a js plugin parameter that requires an array with the values in the input type hidden. The parameter is like:

{
    categories: [here i need to echo the input type hidden value]
}

2 Answers2

1

Use split()

var categories = $("[name= elenco_cat]").val().split(', ');

And in PHP you don't need a loop, just use implode()

$elenco_categorie = implode(', ', array_column($categorie, 'nome'));

This will also prevent the extra , at the end.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you so much sir, last little thing because i'm not practical with js, how can i avoid the final "," that he puts after the splitting? is there a sort of limit? – Simone De Luca Aug 20 '20 at 07:17
  • If you use `implode()` you won't get the final `,`. – Barmar Aug 20 '20 at 07:19
0

You can push every looped value to a defined variable The variable $list will take the new values looped

$list = array();

foreach ($categorie as $cat) {
push_array($list,  $cat['nome']);
}
Ezekiel Arin
  • 115
  • 6