Hi everyone,
I have a bit of an array headache going on. The function does what I want, but since I am not yet to well acquainted with PHP:s array/looping functions, so thereby my question is if there's any part of this function that could be improved from a performance-wise perspective?
$var = myFunction ( array('key1', 'key2', 'key3', '111') );
function myFunction ($keys) {
$prefix = 'prefix_';
$keyCount = count($keys);
// Prefix each key and remove old keys
for($i=0;$i<$keyCount; $i++){
$keys[] = $prefix.$keys[$i];
unset($keys[$i]);
}
// output: array('prefix_key1', 'prefix_key2', 'prefix_key3', '111)
// Get all keys from memcached. Only returns valid keys
$items = $this->memcache->get($keys);
// output: array('prefix_key1' => 'value1', 'prefix_key2' => 'value2', 'prefix_key3'=>'value3)
// note: key 111 was not found in memcache.
// Fill upp eventual keys that are not valid/empty from memcache
$return = $items + array_fill_keys($keys, '');
// output: array('prefix_key1' => 'value1', 'prefix_key2' => 'value2', 'prefix_key3'=>'value3, 'prefix_111' => '')
// Remove the prefixes for each result before returning array to application
foreach ($return as $k => $v) {
$expl = explode($prefix, $k);
$return[$expl[1]] = $v;
unset($return[$k]);
}
// output: array('key1' => 'value1', 'key2' => 'value2', 'key3'=>'value3, '111' => '')
return $return;
}
Thanks a lot!
Edit: Requested psuedo-code:
- Add prefixes to array, since we need to prefix every key to prevent kes being overwritten in memcache
- Get all keys from memcache
- Fill up eventual keys that are not valid, since we would like to avoid any "not-valid-index" errors caused by the fact of a requested key not returned.
- Remove the prefixes to make formatting the outputted keys easier without having to get prefix for each value.