Ad

PHP Array To Javascript Loop Vs Json_encode

- 1 answer

Hello guys i am a newbie laravel develop and in my blade i have a php var $x and this is an array!

My question what is the best method and when to apply each method?

My first metho is loop with foreach for exemple:

 <script>
  var javascript = [];
        @foreach($x as $value)
          javascript[$loop->index] = $value;
        @endforeach
  </script>

My second method is with @json or json_encode

<script>
  var javascript = @json($x);
</script>

What method is the best?? When to aply diferent methods?

Sorry for this newbie question!! Thanks for your help.

Ad

Answer

The most straightforward way is to just use JSON like you did with @json. This is very safe, because JSON syntax always makes for valid JavaScript expression.

It's even mentioned in the documentation, under Displaying Data.

Your first example is unnecessarily complicated and meant only for numeric-indexed arrays, so PHP's associative arrays won't work as expected.

Ad
source: stackoverflow.com
Ad