-4

Is there any way besides for explode to convert a php string that looks like: "[2,0,[]]" into an array?

My array output should be like:

array(2,0,array())

And "[2,0,[1,2,3,4]]" this sting should be:

array(2,0,array(1,2,3,4))

I do not want to use explode because it just seems like to much code for a very simple task. in javascript it is a one liner:

JSON.parse('[2,0,[1,2,3,4]]');
6
  • How is the result supposed to look like? Commented Dec 23, 2015 at 12:49
  • what is your expected output? Commented Dec 23, 2015 at 12:49
  • And what is wrong with explode? In case the character to explode on is used elsewhere, you might use a regex. Commented Dec 23, 2015 at 12:50
  • Expected result is array(2,0,array())? Commented Dec 23, 2015 at 12:50
  • 1
    @SagarNaliyapara, No, here is a JSON string actually, so different solution. Commented Dec 23, 2015 at 13:31

2 Answers 2

8

Your input looks like a JSON string, which can be converted with json_decode() function :

json_decode("[2,0,[]]", true); 

/*
Array (
    0 => 2,
    1 => 0,
    2 => 
    Array (
    ),
)
*/
Sign up to request clarification or add additional context in comments.

3 Comments

thank you. i did not think that would work because it is not valid json.
i should have known that would work because i did that in JavaScript.
@Jay Blanchard oh i thought all json needed to start with { } , ok my bad
0

As specified by Tareq Mahmood json_decode would work but in case you want to do it from scratch:

<?php
$string = "[2,0,[1,2,3,4,]]";

$i = 0;
$array = array();
$handlerCount = 0;
$arrayTmp = array();
$countArr2=0;
while(isset($string[$i])){
        switch($string[$i]){
                case ",":
                        break;
                case "[":
                        $handlerCount++;
                        break;
                case "]":
                        $handlerCount--;
                        break;
                default:
                        if($handlerCount == 1){
                                $array[$i] = (int)$string[$i];
                        }else{
                                $arrayTmp[$countArr2] = (int)$string[$i];
                                $countArr2++;
                        }

        }
        $i++;
}
array_push($array,$arrayTmp);

var_dump($array);
?>

[Proof of concept]

array(3) {
  [1]=>
  int(2)
  [3]=>
  int(0)
  [4]=>
  array(4) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
    [3]=>
    int(4)
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.