I have a very simple PHP array
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
If I dd($array);
out I got
array:3 [▼
"a" => "1"
"b" => "2"
"c" => "3"
]
If I decode dd(json_encode($array));
, I got this
"{"a":"1","b":"2","c":"3"}"
I want to be able to access this variable in my Javascript, So I've tried
console.log($array);
I got
$array is not defined
I'm using Laravel. {{ }} == echo
console.log('{{$array}}');
I got
500 Internal Error
htmlentities() expects parameter 1 to be string, array given (View: /Users/bheng/Sites/portal/resources/views/cpe/index.blade.php)
console.log('{{ json_encode($array)}}');
I got
The page to load, but the data is very bad looking
{"a":"1","b":"2","c":"3"}
console.log(JSON.parse('{{ json_encode($array)}}'));
I got
Uncaught SyntaxError: Unexpected token & in JSON at position 1
console.log(JSON.parse('{{ json_decode($array)}}'));
I got
json_decode() expects parameter 1 to be string, array given
console.log('{{ json_decode($array)}}');
I got
json_decode() expects parameter 1 to be string, array given
I just want to be able to access my array as Javascript Array or JSON in the Javascript.
Can someone please fill me in on this ?
You can use PHP array in JavaScript. It works for the single as well as the multidimensional array. Use the json_encode() method to achieve this.
JavaScript Array indexOf() The indexOf() method searches an array for an element value and returns its position. Note: The first item has position 0, the second item has position 1, and so on.
JavaScript lets us create arrays inside array called Nested Arrays. Nested Arrays have one or many arrays as the element of an array.
The elements in a PHP numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]).
In Blade, {{ $variable }}
will output an escaped version of the string, passed through htmlentities()
to make it safe for use in HTML. You want an unescaped version. You can use {!! $variable !!}
for that:
console.log({!! json_encode($array) !!});
You don't need to add quotes around it, json_encode()
outputs a valid javascript object. It will add quotes where necessary, if you add them yourself you will get the JSON string in your javascript, instead of the JSON object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With