Navigation

Php

How to Map Arrays with array_map()

Transform array elements using array_map() to apply functions to every element, creating powerful data transformation pipelines in PHP.

Table Of Contents

Quick Fix

Array mapping transforms each element using a callback function while maintaining the same array structure. Unlike filtering which removes elements, array_map() always returns an array with the same number of elements, making it perfect for data transformation and formatting operations.

<?php

// Basic transformation
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($n) {
    return $n * $n;
}, $numbers);
// Result: [1, 4, 9, 16, 25]

// Using arrow functions for concise syntax
$doubled = array_map(fn($n) => $n * 2, $numbers);
// Result: [2, 4, 6, 8, 10]

// Transform strings
$names = ['john', 'jane', 'bob', 'alice'];
$capitalized = array_map('ucfirst', $names);
// Result: ['John', 'Jane', 'Bob', 'Alice']

$uppercased = array_map('strtoupper', $names);
// Result: ['JOHN', 'JANE', 'BOB', 'ALICE']

// Complex object transformation
$users = [
    ['first_name' => 'John', 'last_name' => 'Doe', 'age' => 30],
    ['first_name' => 'Jane', 'last_name' => 'Smith', 'age' => 25],
    ['first_name' => 'Bob', 'last_name' => 'Johnson', 'age' => 35]
];

// Create full names
$fullNames = array_map(function($user) {
    return $user['first_name'] . ' ' . $user['last_name'];
}, $users);
// Result: ['John Doe', 'Jane Smith', 'Bob Johnson']

// Transform to different structure
$userProfiles = array_map(function($user) {
    return [
        'name' => $user['first_name'] . ' ' . $user['last_name'],
        'age_group' => $user['age'] < 30 ? 'young' : 'adult',
        'initials' => strtoupper($user['first_name'][0] . $user['last_name'][0])
    ];
}, $users);

// Multiple array processing
$firstNames = ['John', 'Jane', 'Bob'];
$lastNames = ['Doe', 'Smith', 'Johnson'];
$ages = [30, 25, 35];

// Combine multiple arrays
$combinedData = array_map(function($first, $last, $age) {
    return [
        'full_name' => "$first $last",
        'age' => $age,
        'email' => strtolower($first . '.' . $last . '@example.com')
    ];
}, $firstNames, $lastNames, $ages);

// Null callback for array combination
$zipped = array_map(null, $firstNames, $lastNames, $ages);
// Result: [['John', 'Doe', 30], ['Jane', 'Smith', 25], ['Bob', 'Johnson', 35]]

// Real-world examples

// Format prices
$prices = [19.99, 99.95, 149.50, 5.00];
$formattedPrices = array_map(function($price) {
    return '$' . number_format($price, 2);
}, $prices);
// Result: ['$19.99', '$99.95', '$149.50', '$5.00']

// Validate and clean input
$emails = ['  John@EXAMPLE.com  ', 'jane@domain.org', '  invalid-email  ', 'bob@test.co.uk  '];
$cleanEmails = array_map(function($email) {
    $clean = trim(strtolower($email));
    return filter_var($clean, FILTER_VALIDATE_EMAIL) ?: null;
}, $emails);
// Result: ['john@example.com', 'jane@domain.org', null, 'bob@test.co.uk']

// Process file information
$files = ['document.pdf', 'image.jpg', 'script.php', 'data.csv'];
$fileInfo = array_map(function($filename) {
    return [
        'name' => pathinfo($filename, PATHINFO_FILENAME),
        'extension' => pathinfo($filename, PATHINFO_EXTENSION),
        'type' => match(pathinfo($filename, PATHINFO_EXTENSION)) {
            'pdf' => 'document',
            'jpg', 'png', 'gif' => 'image',
            'php' => 'script',
            'csv' => 'data',
            default => 'unknown'
        }
    ];
}, $files);

// Database row transformation
$dbResults = [
    ['user_id' => 1, 'created_at' => '2024-01-15 10:30:00', 'status' => 1],
    ['user_id' => 2, 'created_at' => '2024-01-16 14:20:00', 'status' => 0],
    ['user_id' => 3, 'created_at' => '2024-01-17 09:15:00', 'status' => 1]
];

$apiResponse = array_map(function($row) {
    return [
        'id' => (int)$row['user_id'],
        'created' => date('Y-m-d', strtotime($row['created_at'])),
        'active' => (bool)$row['status'],
        'formatted_date' => date('F j, Y', strtotime($row['created_at']))
    ];
}, $dbResults);

// Nested array mapping
$categories = [
    'electronics' => ['laptop', 'phone', 'tablet'],
    'books' => ['fiction', 'non-fiction', 'textbook'],
    'clothing' => ['shirt', 'pants', 'shoes']
];

$processedCategories = array_map(function($items) {
    return array_map('ucfirst', $items);
}, $categories);

// Mathematical operations
$coordinates = [[1, 2], [3, 4], [5, 6]];
$distances = array_map(function($point) {
    [$x, $y] = $point;
    return sqrt($x * $x + $y * $y);
}, $coordinates);

// Class method mapping
class TextProcessor {
    public static function slugify(string $text): string {
        return strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', trim($text)));
    }
    
    public function addPrefix(string $text): string {
        return 'processed_' . $text;
    }
}

$titles = ['Hello World', 'PHP Array Functions', 'Data Processing'];
$slugs = array_map([TextProcessor::class, 'slugify'], $titles);
// Result: ['hello-world', 'php-array-functions', 'data-processing']

// Instance method mapping
$processor = new TextProcessor();
$prefixed = array_map([$processor, 'addPrefix'], $titles);

// Conditional mapping
$scores = [85, 92, 67, 78, 95, 43, 88];
$grades = array_map(function($score) {
    return match(true) {
        $score >= 90 => 'A',
        $score >= 80 => 'B',
        $score >= 70 => 'C',
        $score >= 60 => 'D',
        default => 'F'
    };
}, $scores);

// Chain mapping operations
$rawData = ['  hello world  ', '  PHP PROGRAMMING  ', '  data analysis  '];
$processed = array_map(
    fn($text) => str_replace(' ', '-', $text),
    array_map('trim', 
        array_map('strtolower', $rawData)
    )
);
// Result: ['hello-world', 'php-programming', 'data-analysis']

// Performance considerations for large arrays
function mapLargeArray(array $data, callable $callback): array {
    // For very large arrays, consider chunking
    $chunkSize = 1000;
    $result = [];
    
    foreach (array_chunk($data, $chunkSize) as $chunk) {
        $result = array_merge($result, array_map($callback, $chunk));
    }
    
    return $result;
}

// Error handling in mapping
function safeMap(array $array, callable $callback): array {
    return array_map(function($item) use ($callback) {
        try {
            return $callback($item);
        } catch (Exception $e) {
            error_log("Mapping error: " . $e->getMessage());
            return null; // or some default value
        }
    }, $array);
}

$riskyData = [1, 0, 5, 0, 3];
$safeResults = safeMap($riskyData, function($n) {
    if ($n === 0) throw new Exception("Division by zero");
    return 10 / $n;
});

// Usage examples
echo "Squared numbers: " . implode(', ', $squared) . "\n";
echo "Full names: " . implode(', ', $fullNames) . "\n";
echo "Formatted prices: " . implode(', ', $formattedPrices) . "\n";
echo "Grades: " . implode(', ', $grades) . "\n";
echo "Processed text: " . implode(', ', $processed) . "\n";

print_r($fileInfo);
print_r($apiResponse);

Behind the Scenes

array_map() applies a callback function to each element and returns a new array with the transformed values. It preserves array keys and can work with multiple arrays simultaneously, making it incredibly versatile for data transformation tasks.

When used with multiple arrays, the callback receives one element from each array at the same position. If arrays have different lengths, shorter arrays are extended with null values. The null callback special case simply combines arrays element by element.

Essential for data formatting, API response transformation, bulk data processing, and functional programming patterns. Combine with other array functions like array_filter() and array_reduce() for powerful data processing pipelines.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Php