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?
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.
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 [].
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With