1

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.

3
  • How does the generated input look like? Commented Mar 23, 2018 at 14:48
  • 1
    Normally if $myArray is an empty array() json_encode should return [] so I'm not sure where the syntax error is coming from. What does the response from json_encode($myArray); look like if empty or rather what is $myArray looking like? Commented Mar 23, 2018 at 14:51
  • It just gives a string Array Commented Mar 23, 2018 at 14:51

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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'.

Comments

1

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);

Comments

0

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 [];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.