Assume that you have a PHP array like this, coming from a mysqli query:
$array = (
'user_id' => 1
'user_name' => 'User',
'user_email' => 'mail@user.com'
);
Now I would like to create an instance of my user class. The constructor takes an array but the keys should be 'id', 'name', and 'email'.
What is the fastest way to edit the array above so that I get a new array like this:
$newArray = (
'id' => 1
'name' => 'User',
'email' => 'mail@user.com'
);
$user = new User($newArray);
Of course I could simply loop through the original $array
and use preg_replace()
like this:
$newArray = array();
foreach ($array as $key => $value) {
$newKey = preg_replace('/^user_/', '', $key);
$newArray[$newKey] = $value;
}
But there surely is a faster way who could solve this problem? At the moment I cannot think of a good way, that's how I ended up here.