user3286430
user3286430

Reputation:

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

I have this variable $csv = '3,6,7,8'; that i need to convert to a square bracketed array of the form $csv_array = [3,6,7,8];

If i explode the csv like $new_array=explode(",",$csv);,it does not give me the array i want.

This is a 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 is false
}

echo '<br/>';
$new_array=explode(",",$csv);

print_r($new_array);
//not what i am looking for

echo '<br/>';

print_r($new_csv);

echo '<br/>';

echo $new_csv;

Upvotes: 0

Views: 626

Answers (2)

zanderwar
zanderwar

Reputation: 3730

As stated by a fellow stacker

RichardBernards - The two 'types' of array are exactly the same in PHP. If you are looking for JSON

An example of using JSON to achieve what it is you require:

To encode:

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

echo $json;

To decode $csv into the normal array you provided it:

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

And then to return it to its original format:

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

See json_encode() for more information, and also see it's opposite json_decode()

Keep in mind that JSON is literally a string and is not compatible associatively in PHP until it is decoded using the json_decode() function mentioned above. With that being said, replacing true with false in the example above would create an object array and multi-dimensional arrays would require them to be referenced differently, e.g. $array->result.

It would also be worth bringing to your attention the beauty of the predefined CSV functions within PHP

Upvotes: 1

Justinas
Justinas

Reputation: 43451

Adding [ and ] to string does not makes it PHP array.

$csv = '3,6,7,8';
var_dump(explode(',', $csv));

array(4) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "6"
  [2]=>
  string(1) "7"
  [3]=>
  string(1) "8"
}

That is equal to ["3", "6", "7", "8"] as PHP array.

To get JSON array form it, use json_encode(explode(',', $csv)). Or simply $jsonArray = "[{$csv}]" if you need JSON array (not PHP array, because it will be simple string).

Upvotes: 0

Related Questions