How to Convert a Php Array to a Javascript array

How to Convert a PHP Array to a Javascript Array is covered in this tutorial. PHP arrays, such as one-dimensional arrays, multidimensional arrays, and associative arrays, can be utilised in JavaScript and can be used in a variety of tasks.

In JavaScript, how to use a one-dimensional PHP array Let’s say we have the PHP array below and want to use it in our JavaScript code: $ user = array (‘Farhad HP’, ’email@farhadhp.ir’);

How to Convert a Php Array to a Javascript array

$ user = array (‘shan HP’, ’email@ShanHp.com);

Using the json encode PHP function, we can convert our PHP array to an array that can be used in JavaScript; thus, our JavaScript code will look like this.

<script type = "text / javascript">
var users = <? php echo json_encode ($ user); ?>;
</script>

Our PHP array has now been converted to a JavaScript array. So, what are you going to do with it now? You presumably know how to utilise JavaScript if you know a little bit about it.

Assuming we want to use only our username from our array, our code will be as follows.

alert (users [0]); // output "Shan HP"
Note: In the above code, I extracted the user name from the array and showed it to the user with the alert function.


How to use php multidimensional array in JavaScript

Suppose we have our user list arrays in PHP as follows and we want to use them in JavaScript as well.

$ users = array (
    array ('Shan HP', 'email@axcore.com'),
    array ('Zubair Qasemi', 'zubair@qasemi.com'),
    array ('Naveed khan', 'naveedd@naveedkhn.com'),
    array ('Ashkan Khan', 'ashkan@khan.com')
);

The code to convert our JavaScript is the same as the previous code (ie we use the json_encode PHP function)

<script type = "text / javascript">
var users = <? php echo json_encode ($ users); ?>;
</script>
Suppose we want to show the name of the second user in the array; So our code will be as follows.

alert (users [1] [0]); // output "zubair Qasemi"
How to use php community array in JavaScript
I converted the previous array to an association array; Note the following codes:


We also use the following code to convert the array, which is the same as the previous two.

<script type = "text / javascript">
var users = <? php echo json_encode ($ users); ?>;
</script>

To use, we do the following; Suppose we want to show the third user's email; So our code will be as follows.

alert (users [2] .email); // output "naveed@khan.com"
%d bloggers like this: