0

i have a var $subject when i print it by echo $subject i get this [["2","subject2","0","0"],["4","ccd","50","5"]]

but when i do echo gettype($subject) i get string

because of this i am not able to use foreach loop in order to iterate over $subject

how can i get it in array [["2","subject2","0","0"],["4","ccd","50","5"]] format

chen yu
  • 65
  • 2
  • 11

2 Answers2

2

You can use json_decode to convert that string into an array:

$subject = '[["2","subject2","0","0"],["4","ccd","50","5"]]';
print_r(json_decode($subject, true));

Output:

Array ( 
    [0] => Array ( [0] => 2 [1] => subject2 [2] => 0 [3] => 0 ) 
    [1] => Array ( [0] => 4 [1] => ccd [2] => 50 [3] => 5 ) 
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
0

As mentioned by @nick use the json_decode function to make it an array.

$subject = '[["2","subject2","0","0"],["4","ccd","50","5"]]';
$stringToArray = json_decode($subject, true);
foreach($stringToArray as $key => $value){
    print_r($value);echo '<hr>';
}
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20