How can one efficiently filter and transfer specific values from an associative array to a new array in PHP?
To efficiently filter and transfer specific values from an associative array to a new array in PHP, you can use the array_filter function along with a custom callback function that defines the filtering criteria. The callback function should return true for the values you want to keep in the new array. This approach allows you to selectively transfer values based on your specified conditions.
// Original associative array
$originalArray = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
// Filter and transfer specific values to a new array
$newArray = array_filter($originalArray, function($value, $key) {
// Define the filtering criteria, e.g., keep values starting with 'value'
return strpos($value, 'value') === 0;
}, ARRAY_FILTER_USE_BOTH);
print_r($newArray);