Skip to content

Instantly share code, notes, and snippets.

@dyazincahya
Created October 19, 2018 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyazincahya/802772e727fd1220f50e06717d99273d to your computer and use it in GitHub Desktop.
Save dyazincahya/802772e727fd1220f50e06717d99273d to your computer and use it in GitHub Desktop.
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