3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php function JSEscape($s) { static $aSearch = array("\xe2\x80\xa9", "\\", "'", "\"", "\r\n", "\r", "\n", "\xe2\x80\xa8", "*/", "</"); static $aReplace = array(" ", "\\\\", "\\'", '\\"', "\n", "\n", "\\n", "\\n", "*\\/", "<\\/"); $val = str_replace($aSearch, $aReplace, $s); return $val; } function PhpToJSObject($arData, $bWS = false, $bSkipTilda = false, $bExtType = false) { static $aSearch = array("\r", "\n"); $bExtType = !!$bExtType; switch(gettype($arData)) { case "string": if(strpbrk($arData, "'\"\n\r<\\\x80") !== false) return "'".JSEscape($arData)."'"; else return "'".$arData."'"; case "array": $i = -1; $j = -1; foreach($arData as $j => $temp) { $i++; if ($j !== $i) break; } if($j === $i) { foreach($arData as $key => $value) { switch(gettype($value)) { case "string": if(strpbrk($value, "'\"\n\r<\\\x80") !== false) $arData[$key] = "'".JSEscape($value)."'"; else $arData[$key] = "'".$value."'"; break; case "array": $arData[$key] = PhpToJSObject($value, $bWS, $bSkipTilda, $bExtType); break; case "boolean": if($value === true) $arData[$key] = 'true'; else $arData[$key] = 'false'; break; case "integer": case "double": if ($bExtType) { $arData[$key] = $value; break; } default: if(strpbrk($value, "'\"\n\r<\\\x80") !== false) $arData[$key] = "'".JSEscape($value)."'"; else $arData[$key] = "'".$value."'"; break; } } return '['.implode(',', $arData).']'; } $sWS = ','.($bWS ? "\n" : ''); $res = ($bWS ? "\n" : '').'{'; $first = true; foreach($arData as $key => $value) { if ($bSkipTilda && substr($key, 0, 1) == '~') continue; if($first) $first = false; else $res .= $sWS; if(strpbrk($key, "'\"\n\r<\\\x80") !== false) $res .= "'".str_replace($aSearch, '', JSEscape($key))."':"; else $res .= "'".$key."':"; switch(gettype($value)) { case "string": if(strpbrk($value, "'\"\n\r<\\\x80") !== false) $res .= "'".JSEscape($value)."'"; else $res .= "'".$value."'"; break; case "array": $res .= PhpToJSObject($value, $bWS, $bSkipTilda, $bExtType); break; case "boolean": if($value === true) $res .= 'true'; else $res .= 'false'; break; case "integer": case "double": if ($bExtType) { $res .= $value; break; } default: if(strpbrk($value, "'\"\n\r<\\\x80") !== false) $res .= "'".JSEscape($value)."'"; else $res .= "'".$value."'"; break; } } $res .= ($bWS ? "\n" : '').'}'; return $res; case "boolean": if($arData === true) return 'true'; else return 'false'; case "integer": case "double": if ($bExtType) { return $arData; } default: if(strpbrk($arData, "'\"\n\r<\\\x80") !== false) return "'".JSEscape($arData)."'"; else return "'".$arData."'"; } } $a=array( "a0" => "b", "a1" => "b", "a2" => "b", "a3" => "b", "b" => "c'", "c" => array(1,2,3), "d" => true, "e" => 15.5 ); print_r(PhpToJSObject($a));
based on MNTsr
Output for 5.4.0 - 5.6.28, hhvm-3.10.0 - 3.12.0, 7.0.0 - 7.1.0
{'a0':'b','a1':'b','a2':'b','a3':'b','b':'c\'','c':['1','2','3'],'d':true,'e':'15.5'}