lewis4u
lewis4u

Reputation: 15037

Passing optional array from PHP to jQuery

I have a problem if this optional array is empty:

<script>
    var parsedArray = JSON.parse('<?php echo json_encode($myArray); ?>');
    console.log(parsedArray );
</script>

All is fine if array is NOT empty, but the problem comes if there are no values in array;

Uncaught SyntaxError: Unexpected token A in JSON at position 0

Console.log just spits Array out if array is empty.

I want to learn how is this done properly. How to pass an empty array to jQuery so I can run myArray.length function on it for example and so that it returns 0 if it is empty.

Upvotes: 1

Views: 78

Answers (4)

lewis4u
lewis4u

Reputation: 15037

I think it is not necessary to do the if statement i figured it out and my problem was that I did the json_encode($myArray) in PHP code and then JSON.parse in javascript

it works like this without problems:

in PHP just declare the array

$myArray = [];

and in php file under script spit it out like this:

var myArray = <?= json_encode($myArray) ?>;

And now even if array is empty it will spit out [];

Upvotes: 0

Terry
Terry

Reputation: 66113

You can use tenary operators when echoing out your $myArray. If it is empty, you can simply pass null to JSON.parse instead, i.e.:

var parsedArray = JSON.parse('<?php echo !empty($myArray) ? json_encode($myArray) : "null"; ?>');
console.log(parsedArray);

Upvotes: 2

Racil Hilan
Racil Hilan

Reputation: 25351

You can check $myArray when echoing it out and do something if it is empty. What to do depends on how you will be using parsedArray afterwords. You can pass an empty array []:

var parsedArray = JSON.parse('<?php echo !empty($myArray)? json_encode($myArray) : "[]"; ?>');
console.log(parsedArray);

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

With the above answer, I would also add the 's to the PHP:

var parsedArray = JSON.parse(<?php echo !empty($myArray) ? "'" . json_encode($myArray) . "'" : "null"; ?>);
console.log(parsedArray);

Because we wouldn't use null as 'null'.

Upvotes: 1

Related Questions