What is the correct way to extract the first two characters from each element in an array in PHP?

To extract the first two characters from each element in an array in PHP, you can use a combination of array_map() and substr() functions. The array_map() function will iterate over each element in the array and apply a callback function to extract the first two characters using the substr() function.

// Sample array
$originalArray = ['apple', 'banana', 'cherry'];

// Use array_map() to apply substr() function to extract first two characters from each element
$extractedArray = array_map(function($element) {
    return substr($element, 0, 2);
}, $originalArray);

// Output the extracted array
print_r($extractedArray);