Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Function php string array to real array
<?php
// function
function strarr_to_array($a, $t = ''){
$arr = [];
$a = ltrim($a, '[');
$a = ltrim($a, 'array(');
$a = rtrim($a, ']');
$a = rtrim($a, ')');
$tmpArr = explode(",", $a);
foreach ($tmpArr as $v) {
if($t == 'keys'){
$tmp = explode("=>", $v);
$k = $tmp[0]; $nv = $tmp[1];
$k = trim(trim($k), "'");
$k = trim(trim($k), '"');
$nv = trim(trim($nv), "'");
$nv = trim(trim($nv), '"');
$arr[$k] = $nv;
} else {
$v = trim(trim($v), "'");
$v = trim(trim($v), '"');
$arr[] = $v;
}
}
return $arr;
}
// usage
$test = '["me","and","you","just","a","friend","Ohhhhhhhhh!","sad"]';
echo "<pre>";
print_r(strarr_to_array($test));
// result
Array
(
[0] => me
[1] => and
[2] => you
[3] => just
[4] => a
[5] => friend
[6] => Ohhhhhhhhh!
[7] => sad
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.