Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String with square brackets to PHP Array

Tags:

arrays

php

I have a string, values are in brackets and separated with comma, like array string:

Example:

[[["Name" , "ID"] , [12]] , ["Test" , 78] , 0]

How to convert this string to PHP array?

like image 442
Hapter Avatar asked Jun 26 '14 20:06

Hapter


People also ask

How do I convert a string to an array in PHP?

PHP | str_split() Function. The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.

What is difference between array and [] in PHP?

Note: Only the difference in using [] or array() is with the version of PHP you are using. In PHP 5.4 you can also use the short array syntax, which replaces array() with [].

What are brackets in PHP?

In PHP, elements can be added to the end of an array by attaching square brackets ([]) at the end of the array's name, followed by typing the assignment operator (=), and then finally by typing the element to be added to the array. So far in our PHP programming, we've been thinking about individual pieces of data.


1 Answers

That's a JSON string representation of an array, use json_decode():

$array = json_decode($string);    
print_r($array);

Yields:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Name
                    [1] => ID
                )
            [1] => Array
                (
                    [0] => 12
                )
        )
    [1] => Array
        (
            [0] => Test
            [1] => 78
        )
    [2] => 0
)

If it had any { } that would be an object and decoded as a stdClass object in PHP unless you pass true to json_decode() to force an array.

Since it's structured as a PHP array (as of PHP 5.4), this works as well (don't use eval on untrusted data). There is absolutely no reason to do this, it's just illustrative:

eval("\$array = $string;");
print_r($array);
like image 102
AbraCadaver Avatar answered Oct 13 '22 08:10

AbraCadaver