php - How would i convert a comma seperated list to a square bracket array -


i have variable $csv = '3,6,7,8'; need convert square bracketed array of form $csv_array = [3,6,7,8];

if explode csv $new_array=explode(",",$csv);,it not give me array want.

this running example http://3v4l.org/kyc0g

the code

$csv = '3,6,7,8'; $new_csv = '['.$csv.']';  if(is_array($new_csv)){ echo 'true'; } else{ echo 'false'; //this false }  echo '<br/>'; $new_array=explode(",",$csv);  print_r($new_array); //not looking  echo '<br/>';  print_r($new_csv);  echo '<br/>';  echo $new_csv; 

as stated fellow stacker

richardbernards - 2 'types' of array same in php. if looking json

an example of using json achieve require:

to encode:

$csv = '3,6,7,8'; $array = explode(",", $csv); $json = json_encode($array);  echo $json; 

to decode $csv normal array provided it:

$decoded = json_decode($json, true); var_dump($decoded); 

and return original format:

$csv = implode(',', $decoded); 

see json_encode() more information, , see it's opposite json_decode()

keep in mind json literally string , not compatible associatively in php until decoded using json_decode() function mentioned above. being said, replacing true false in example above create object array , multi-dimensional arrays require them referenced differently, e.g. $array->result.

it worth bringing attention beauty of predefined csv functions within php


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -