-3

I am New to this. I want to create text file in PHP for that I need two array for Clint side. Problem is that I have passed the array from JavaScript to PHP but In PHP it does convert into single string of array of javascript.

test.html

<form method="post" id="theform" action="example.php">
    <!-- your existing form fields -->

    <input type="hidden" id="markers" name="markers">

    <button>Submit</button>
</form>

<script>
    window.onload = function () {
        var form = document.getElementById('theform');
        form.addEventListener('submit', function () {
            var markersField = document.getElementById('markers');
            var markers = [1, 2, 3];
            markersField.value = JSON.stringify(markers);
        });
    }
</script>

example.php

<?php 
    $array=json_decode($_POST['markers']);
    foreach($array as $value){
        print $value;
    }
?>

output of example.php

123

Expected Output

$array[0] = 1;
$array[1] = 2;
$array[2] = 3;
  • Let's put it this way: if you had `$array = [1, 2, 3];` instead, you'd get the exact same output from that foreach loop (which only prints the values) –  Feb 28 '21 at 19:19

1 Answers1

1

The expected output from your code is indeed 123, because you did actually not print the array $array, but the single values of the array. To show the array, you would need to use print_r() or var_dump() and view the source code in the browser or use HTML (<pre><?php print_r($array);?></pre>) for a prettier print.

Additionally, to make sure json_decode() doesn't create an object but an array, make sure to enable the parameter $assoc. The solution is:

PHP 8

<?php 
$array = json_decode($_POST['markers'], assoc: true);

print('<pre>');
print_r($array);
print('</pre>');

PHP 7 or lower

<?php 
$array = json_decode($_POST['markers'], true);

print('<pre>');
print_r($array);
print('</pre>');
Tintenfisch
  • 58
  • 1
  • 4