Skip to content

Instantly share code, notes, and snippets.

@unicornist
Last active May 15, 2016 13:02
Show Gist options
  • Save unicornist/86df680bd16354a7c71dd6012538a4ed to your computer and use it in GitHub Desktop.
Save unicornist/86df680bd16354a7c71dd6012538a4ed to your computer and use it in GitHub Desktop.
simulator of PHP `serialize` function in pure JavaScript
function phpSerialize(obj){ // e.g. a:1{i:2;s:5:"22222";}
var props = [];
for(var prop in obj)
props.push(_phpSerializeVar(prop)+_phpSerializeVar(obj[prop]));
return 'a:'+props.length+':{'+props.join('')+'}';
}
function _phpSerializeVar(prop){ // e.g. i:2; e.g. s:5:"22222";
return (isNaN(prop) && prop.length) ?
's:' + prop.length + ':"' + prop + '";' :
'i:' + prop + ';' ;
}
console.log(phpSerialize({2: 123, '8': 'test', 'field':'value'}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment