Can I use a javascript value inside json_encode

✔ Recommended Answer

JavaScript executes later, after PHP has produced the page (and JS script). So just let PHP produce the whole array in the JS script and add the code for JS to grab the element at the intended index:

valor = 1;var arrayreceitas = <?= json_encode(array_column($array_seccao, 0)); ?>[valor];

Obviously, this is only useful when the JS script will have a dynamically determined valor. If it is a constant like here, then PHP would just apply that index first and JS would no longer need valor = 1.


Answered By: trincot

Method #2

Yes, you can use a JavaScript value inside json_encode() function in PHP by first assigning the value to a variable in JavaScript, and then passing that variable as an argument to json_encode().

For example, if you have a JavaScript variable named myValue that contains a string value, you can encode it as a JSON string in PHP like this:

<?php $myValue = "<script>var myValue = 'Hello World'; document.write(myValue);</script>"; $json = json_encode($myValue); echo $json; // Output: "{\"myValue\":\"Hello World\"}" ?>

In the example above, the json_encode() function is used to encode the value of the $myValue variable, which contains a JavaScript string value. The resulting JSON string can then be used in PHP or passed to JavaScript code as needed.

It's important to note that the JSON data format requires values to be in a specific format and escaping is used for some characters, so the data should be properly formatted and escaped before being encoded using json_encode().


Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755