-2

I am asking about the best approach converting string formula like that JSON input ["num1","num2","num3",...] to array in PHP 7 and in JS the array should be like that

$tobeconverted= "[\"1\",\"2\",\"3\"]" ; // consider escape character so ["1","2","3"] 
$number= array("1", "2", "3"); 
Mazen Embaby
  • 1,255
  • 11
  • 18

2 Answers2

2

Conversion between "JS data" (JSON) and PHP can be done with json_encode and json_decode

<?php
$number= array("1", "2", "3");
$json = json_encode($number);
echo $json;

# ["1","2","3"]

$array = json_decode($json);
var_dump($array);

# array(3) {
#  [0]=>
#  string(1) "1"
#  [1]=>
#  string(1) "2"
#  [2]=>
#  string(1) "3"
# }
Michel Feldheim
  • 17,625
  • 5
  • 60
  • 77
0

Here is a solution I found. Hope it helps you.
PHP:

<?php
    $tobeconverted= "[\"1\",\"2\",\"3\"]";
    $arraystring = substr($tobeconverted, 1, strlen($tobeconverted) - 2);
    $array = explode(",", $arraystring);
    foreach ($array as $item) {
        echo $item . '<br/>';
    }
?>

JS:

  var tobeConverted = "[\"3\",\"4\",\"5\"]";  
  var array = JSON.parse(tobeConverted);