0

I have a number of strings, that contain the bracket literals:

0 => string '[139432,97]' (length=18)
1 => string '[139440,99]' (length=18)

I need to create string arrays of [139432,97] and [139440,99].

I've tried using json_decode(), but while it works, it creates arrays as float or int using the above data, however I want them as strings.

array (size=2)
0 => float 139432
1 => int 97

array (size=2)
0 => float 139440
1 => int 97

3 Answers 3

1

You can put double quotes around the values e.g.

0 => string '["139432","97"]' (length=22)
1 => string '["139440","99"]' (length=22)

This way when you json_decode they should be strings.

Edit:

OK I thought you could control the input - if not then a simple trim and explode could do:

explode(',', trim('[139432,97]', '[]'));

array(2) {
  [0]=>
  string(6) "139432"
  [1]=>
  string(2) "97"
}

Is that enough?

Sign up to request clarification or add additional context in comments.

2 Comments

I would have to programatically add those quotes around the values because the data is coming from external source as is
OK I modified the answer above
1

Just combining what you already now (json_decode) and what @AlixAxel suggested here you can extract those values to string link:

$subject = '[139432,97]';
$convertedToArrayOfStrings = array_map('strval', json_decode($subject));

or

$convertedToArrayOfString = array_map(function($item){return (string) $item;}, json_decode($subject));

for better performance, see the comment bellow please :)

1 Comment

And if you are concern about performance, based on what i just learned from @KimHogeling's comment on here and this you can replace the strval with an anonymous method and cast your values e.g. $convertedToArrayOfString = array_map(function($item){return (string) $item;}, json_decode($subject));
0

Why not try with loop and use explode function:

$array = array('139432,97', '139440,99');
$finalArray = array();

$i = 0;
foreach ($array as $arr) {
    $explode = explode(",", $arr);
    $j = 0;
    foreach ($explode as $exp) {
       $finalArray[$i][$j] = (int)$exp;
       $j++;
    }
    $i++;
}

1 Comment

I had tried explode, but because the data is coming externally, the brackets are included, so I would need to massage it further, to use what you have on first line

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.