3v4l.org

run code in 300+ PHP versions simultaneously
<?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 "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));
Output for 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.7, 7.2.29 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.27, 8.2.0 - 8.2.17, 8.3.0 - 8.3.4
{'a0':'b','a1':'b','a2':'b','a3':'b','b':'c\'','c':['1','2','3'],'d':true,'e':'15.5'}

preferences:
177.3 ms | 404 KiB | 263 Q