My PHP script is receiving data from an HTML input as an array:
<input type="checkbox" name="value[]" value="1" />
<input type="checkbox" name="value[]" value="2" />
<input type="checkbox" name="value[]" value="3" />
...
My current method of serialization is as such:
<?php
class DataClass {
private $separator = ",";
private function sanitize($input){
$patterns = array(
'/^'.$this->separator.'/',
'/'.$this->separator.$this->separator.'/',
'/'.$this->separator.'$/'
);
$replacements = array(
'',
$this->separator,
''
);
return preg_replace($patterns, $replacements, $input);
}
public function deserialize($input){
return explode($this->separator, $this->sanitize($input));
}
private function serialize($input){
$bucket = array();
if(is_array($input)):
foreach($input as $value){
if(!empty($value)):
array_push($bucket, $value);
endif;
}
return $this->sanitize(implode($this->separator, $bucket));
else:
return "";
endif;
}
public function store($formdata) {
$formdata['value'] = empty($formdata['value']) ? '' : $this->serialize($formdata['value']);
// save $formdata to database
}
}
?>
So, after reading this post my questions are these:
- What is the best way to optimize the efficiency of the existing code?
- Would there be any performance benefits to using a different means of converting the simple indexed array into something that can be stored in the database?
- How would using a BLOB column type compare with the varchar(255) that I am getting away with currently?
- Since it is not an associative array, would
json_encode
even be the right method, or is it just overkill?