Skip to main content

Course Progress

Loading...

PHP Array Manipulation: Creating and Working with Arrays

Duration: 60 minutes
Module 2: Arrays and Data Manipulation

Learning Objectives

  • Master PHP array operations
  • Work with different array types
  • Use array functions effectively
  • Manipulate complex data structures

Understanding PHP Arrays

Welcome to our exploration of PHP array manipulation! Arrays are one of the most versatile and powerful data structures in PHP. Think of arrays as organized containers that can store multiple values under a single variable name, similar to how a filing cabinet organizes folders or how a toolbox stores different tools.

In this lesson, we'll learn how to create, manipulate, and transform arrays using PHP's built-in functions. These skills are essential for any PHP developer, especially when working with WordPress, which heavily relies on arrays for storing and processing data.

Basic Array Structure

Indexed Array Index 0 Index 1 Index 2 Index 3 Index 4 "Apple" "Banana" "Cherry" "Dragon fruit" "Elderberry" Associative Array "name" "age" "city" "email" "active" "John Doe" 28 "New York" "john@example.com" true

Creating Arrays in PHP

Before we dive into manipulation functions, let's review the basics of creating arrays in PHP:

Creating Indexed Arrays

// Method 1: Using array() function
$fruits = array("Apple", "Banana", "Cherry", "Dragon fruit", "Elderberry");

// Method 2: Using short array syntax (PHP 5.4+) - Recommended
$fruits = ["Apple", "Banana", "Cherry", "Dragon fruit", "Elderberry"];

// Method 3: Adding elements individually
$fruits = [];
$fruits[] = "Apple";
$fruits[] = "Banana";
$fruits[] = "Cherry";

// Accessing elements
echo $fruits[0]; // Outputs: Apple
echo $fruits[2]; // Outputs: Cherry

Creating Associative Arrays

// Method 1: Using array() function
$user = array(
    "name" => "John Doe",
    "age" => 28,
    "city" => "New York",
    "email" => "john@example.com",
    "active" => true
);

// Method 2: Using short array syntax (PHP 5.4+) - Recommended
$user = [
    "name" => "John Doe",
    "age" => 28,
    "city" => "New York",
    "email" => "john@example.com",
    "active" => true
];

// Method 3: Adding elements individually
$user = [];
$user["name"] = "John Doe";
$user["age"] = 28;
$user["city"] = "New York";

// Accessing elements
echo $user["name"]; // Outputs: John Doe
echo $user["city"]; // Outputs: New York

Creating Multidimensional Arrays

// Multidimensional array example
$employees = [
    [
        "name" => "John Doe",
        "position" => "Developer",
        "skills" => ["PHP", "JavaScript", "MySQL"]
    ],
    [
        "name" => "Jane Smith",
        "position" => "Designer",
        "skills" => ["Photoshop", "Illustrator", "CSS"]
    ]
];

// Accessing elements
echo $employees[0]["name"]; // Outputs: John Doe
echo $employees[1]["skills"][0]; // Outputs: Photoshop

Essential Array Manipulation Functions

PHP provides a rich set of functions specifically designed for working with arrays. Let's explore the key functions you'll use most frequently:

Adding and Removing Elements

array_push() - Add Element(s) to the End

The array_push() function adds one or more elements to the end of an array.

Diagram
Apple Banana Cherry Apple Banana Cherry Dragon fruit Elderberry $fruits, 'Dragon fruit', 'Elderberry
$fruits = ["Apple", "Banana", "Cherry"];

// Add one element
array_push($fruits, "Dragon fruit");

// Add multiple elements
array_push($fruits, "Elderberry", "Fig");

print_r($fruits);
// Outputs:
// Array ( [0] => Apple [1] => Banana [2] => Cherry 
//         [3] => Dragon fruit [4] => Elderberry [5] => Fig )

Alternative approach: Use the array bracket notation for adding a single element. This is actually slightly faster than array_push() for single elements.

$fruits[] = "Grape"; // Adds "Grape" to the end of the array

array_pop() - Remove the Last Element

The array_pop() function removes the last element from an array and returns it.

Diagram
Apple Banana Cherry Apple Banana Returned: Cherry $fruits
$fruits = ["Apple", "Banana", "Cherry"];

$last_fruit = array_pop($fruits);

echo "Removed fruit: " . $last_fruit; // Outputs: Removed fruit: Cherry
print_r($fruits);
// Outputs: Array ( [0] => Apple [1] => Banana )

array_unshift() - Add Element(s) to the Beginning

The array_unshift() function adds one or more elements to the beginning of an array.

Diagram
Banana Cherry Apple Banana Cherry $fruits, 'Apple
$fruits = ["Banana", "Cherry"];

// Add one element to the beginning
array_unshift($fruits, "Apple");

// Add multiple elements to the beginning
array_unshift($fruits, "Strawberry", "Raspberry");

print_r($fruits);
// Outputs:
// Array ( [0] => Strawberry [1] => Raspberry [2] => Apple 
//         [3] => Banana [4] => Cherry )

array_shift() - Remove the First Element

The array_shift() function removes the first element from an array and returns it.

Diagram
Apple Banana Cherry Banana Cherry Returned: Apple $fruits
$fruits = ["Apple", "Banana", "Cherry"];

$first_fruit = array_shift($fruits);

echo "Removed fruit: " . $first_fruit; // Outputs: Removed fruit: Apple
print_r($fruits);
// Outputs: Array ( [0] => Banana [1] => Cherry )

Array Information and Analysis

count() - Count Array Elements

The count() function returns the number of elements in an array.

$fruits = ["Apple", "Banana", "Cherry", "Dragon fruit"];

echo "Number of fruits: " . count($fruits); // Outputs: Number of fruits: 4

// With multidimensional arrays
$nested_array = [1, 2, [3, 4, 5]];
echo "Count: " . count($nested_array); // Outputs: Count: 3
echo "Recursive count: " . count($nested_array, COUNT_RECURSIVE); // Outputs: Recursive count: 5

in_array() - Check if Value Exists

The in_array() function checks if a value exists in an array. It returns true if the value is found, false otherwise.

$fruits = ["Apple", "Banana", "Cherry"];

if (in_array("Banana", $fruits)) {
    echo "Banana is in the fruit basket!";
} else {
    echo "No bananas today!";
}
// Outputs: Banana is in the fruit basket!

// Strict comparison (checking type as well)
$numbers = [1, 2, "3"];
var_dump(in_array(3, $numbers)); // Outputs: bool(true) - loose comparison
var_dump(in_array(3, $numbers, true)); // Outputs: bool(false) - strict comparison

array_key_exists() - Check if Key Exists

The array_key_exists() function checks if a specified key exists in an array.

$user = [
    "name" => "John Doe",
    "age" => 28,
    "city" => "New York"
];

if (array_key_exists("age", $user)) {
    echo "The user's age is: " . $user["age"];
} else {
    echo "Age information is not available.";
}
// Outputs: The user's age is: 28

array_keys() - Get Array Keys

The array_keys() function returns all the keys from an array.

$user = [
    "name" => "John Doe",
    "age" => 28,
    "city" => "New York"
];

$keys = array_keys($user);
print_r($keys);
// Outputs: Array ( [0] => name [1] => age [2] => city )

// Get keys for a specific value
$numbers = [10, 20, 30, 20, 40, 20];
$keys_for_20 = array_keys($numbers, 20);
print_r($keys_for_20);
// Outputs: Array ( [0] => 1 [1] => 3 [2] => 5 )

array_values() - Get Array Values

The array_values() function returns all the values from an array.

$user = [
    "name" => "John Doe",
    "age" => 28,
    "city" => "New York"
];

$values = array_values($user);
print_r($values);
// Outputs: Array ( [0] => John Doe [1] => 28 [2] => New York )

array_search() - Search for Value

The array_search() function searches for a value in an array and returns the key if found.

$fruits = ["Apple", "Banana", "Cherry", "Dragon fruit"];

$key = array_search("Cherry", $fruits);
echo "Cherry is at position: " . $key; // Outputs: Cherry is at position: 2

// If not found, returns false
$key = array_search("Mango", $fruits);
var_dump($key); // Outputs: bool(false)

Array Transformation and Manipulation

array_merge() - Merge Arrays

The array_merge() function merges one or more arrays into a single array.

$fruits1 = ["Apple", "Banana", "Cherry"];
$fruits2 = ["Dragon fruit", "Elderberry"];
$vegetables = ["Carrot", "Broccoli"];

$all_food = array_merge($fruits1, $fruits2, $vegetables);
print_r($all_food);
/* Outputs:
Array (
    [0] => Apple
    [1] => Banana
    [2] => Cherry
    [3] => Dragon fruit
    [4] => Elderberry
    [5] => Carrot
    [6] => Broccoli
)
*/

// With associative arrays, same keys will be overwritten
$settings1 = ["theme" => "light", "sidebar" => "left"];
$settings2 = ["theme" => "dark", "notifications" => true];

$merged_settings = array_merge($settings1, $settings2);
print_r($merged_settings);
/* Outputs:
Array (
    [theme] => dark
    [sidebar] => left
    [notifications] => 1
)
*/

array_combine() - Combine Keys and Values

The array_combine() function creates a new array using one array for keys and another for values.

$keys = ["name", "age", "city"];
$values = ["John Doe", 28, "New York"];

$user = array_combine($keys, $values);
print_r($user);
/* Outputs:
Array (
    [name] => John Doe
    [age] => 28
    [city] => New York
)
*/

array_slice() - Extract Part of an Array

The array_slice() function extracts a slice of an array.

$fruits = ["Apple", "Banana", "Cherry", "Dragon fruit", "Elderberry", "Fig"];

// Get 3 items starting at position 2
$slice1 = array_slice($fruits, 2, 3);
print_r($slice1);
// Outputs: Array ( [0] => Cherry [1] => Dragon fruit [2] => Elderberry )

// Get all items from position 3 to the end
$slice2 = array_slice($fruits, 3);
print_r($slice2);
// Outputs: Array ( [0] => Dragon fruit [1] => Elderberry [2] => Fig )

// Get the last 2 items using negative offset
$slice3 = array_slice($fruits, -2);
print_r($slice3);
// Outputs: Array ( [0] => Elderberry [1] => Fig )

array_splice() - Remove and Replace Elements

The array_splice() function removes a portion of the array and replaces it with something else.

$fruits = ["Apple", "Banana", "Cherry", "Dragon fruit", "Elderberry"];

// Remove 2 items starting at position 1
array_splice($fruits, 1, 2);
print_r($fruits);
// Outputs: Array ( [0] => Apple [1] => Dragon fruit [2] => Elderberry )

$fruits = ["Apple", "Banana", "Cherry", "Dragon fruit", "Elderberry"];

// Replace 2 items starting at position 1 with new items
array_splice($fruits, 1, 2, ["Blueberry", "Blackberry"]);
print_r($fruits);
// Outputs: Array ( [0] => Apple [1] => Blueberry [2] => Blackberry 
//                  [3] => Dragon fruit [4] => Elderberry )

$fruits = ["Apple", "Banana", "Cherry", "Dragon fruit"];

// Insert items without removing any (length = 0)
array_splice($fruits, 2, 0, ["Blueberry", "Blackberry"]);
print_r($fruits);
// Outputs: Array ( [0] => Apple [1] => Banana [2] => Blueberry 
//                  [3] => Blackberry [4] => Cherry [5] => Dragon fruit )

array_reverse() - Reverse Array Order

The array_reverse() function returns an array in reverse order.

$numbers = [1, 2, 3, 4, 5];

$reversed = array_reverse($numbers);
print_r($reversed);
// Outputs: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )

// Preserve keys
$user = [
    "name" => "John",
    "age" => 28,
    "city" => "New York"
];

$reversed_user = array_reverse($user, true);
print_r($reversed_user);
/* Outputs:
Array (
    [city] => New York
    [age] => 28
    [name] => John
)
*/

array_unique() - Remove Duplicate Values

The array_unique() function removes duplicate values from an array.

$numbers = [1, 2, 3, 2, 4, 3, 5, 1];

$unique_numbers = array_unique($numbers);
print_r($unique_numbers);
// Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [4] => 4 [6] => 5 )
// Note that the original keys are preserved

array_filter() - Filter Elements

The array_filter() function filters elements of an array using a callback function.

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Get only even numbers
$even_numbers = array_filter($numbers, function($value) {
    return $value % 2 === 0;
});

print_r($even_numbers);
// Outputs: Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )
// Note that the original keys are preserved

// Remove empty values (default behavior when no callback is provided)
$values = ["apple", "", 0, null, false, "banana"];
$filtered = array_filter($values);

print_r($filtered);
// Outputs: Array ( [0] => apple [5] => banana )

array_map() - Apply Function to All Elements

The array_map() function applies a callback function to each element of an array.

$numbers = [1, 2, 3, 4, 5];

// Square each number
$squared = array_map(function($value) {
    return $value * $value;
}, $numbers);

print_r($squared);
// Outputs: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )

// Capitalize each word
$words = ["apple", "banana", "cherry"];
$capitalized = array_map('ucfirst', $words);

print_r($capitalized);
// Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry )

Challenge: Create and Manipulate Arrays with PHP

Now let's apply what we've learned by solving a practical problem using George Polya's four-step problem-solving method.

Problem Statement

You need to create a function that processes a list of user records and transforms it into a format suitable for display on a WordPress dashboard. The function should:

  1. Accept an array of user records, each containing 'name', 'email', 'role', and 'last_login' fields
  2. Remove any duplicate users (based on email)
  3. Filter out inactive users (those who haven't logged in for more than 30 days)
  4. Sort users by role importance (admin > editor > author > subscriber)
  5. Format the data for display by adding a 'display_name' field that combines the name and role
  6. Return the processed array

Solving the Challenge

Step 1: Understand the Problem

Let's break down what we need to accomplish:

  • Input: Array of user records with specific fields
  • Output: Processed array with filtered, sorted, and formatted user records
  • Processing steps: Remove duplicates, filter inactive users, sort by role, add display format

Here's an example of what the input and output might look like:

// Example input
$users = [
    [
        "name" => "John Doe",
        "email" => "john@example.com",
        "role" => "editor",
        "last_login" => "2023-05-10"
    ],
    [
        "name" => "Jane Smith",
        "email" => "jane@example.com",
        "role" => "admin",
        "last_login" => "2023-05-20"
    ],
    // More user records...
];

// Expected output
$processed_users = [
    [
        "name" => "Jane Smith",
        "email" => "jane@example.com",
        "role" => "admin",
        "last_login" => "2023-05-20",
        "display_name" => "Jane Smith (Admin)"
    ],
    [
        "name" => "John Doe",
        "email" => "john@example.com",
        "role" => "editor",
        "last_login" => "2023-05-10",
        "display_name" => "John Doe (Editor)"
    ],
    // More processed records...
];

Step 2: Devise a Plan

Let's create a step-by-step approach to solve this problem:

  1. Create a function that accepts the user records array as input
  2. Create a new array to store unique users (using email as the key to ensure uniqueness)
  3. Calculate the cutoff date for inactive users (30 days ago)
  4. Loop through each user record:
    • Skip if the email already exists in our new array
    • Skip if the last login is older than the cutoff date
    • Add a display_name field combining name and role
    • Store the user in our new array with email as key
  5. Define a role priority mapping for sorting
  6. Sort the array by role priority
  7. Reset array keys and return the final array

Step 3: Implement the Solution

/**
 * Process user records for dashboard display
 * 
 * @param array $users Array of user records
 * @return array Processed user records
 */
function process_users_for_dashboard($users) {
    // Step 1: Initialize variables
    $processed_users = [];
    $cutoff_date = date('Y-m-d', strtotime('-30 days'));
    
    // Step 2: Process each user
    foreach ($users as $user) {
        // Skip if missing required fields
        if (!isset($user['email']) || !isset($user['role']) || !isset($user['last_login'])) {
            continue;
        }
        
        $email = $user['email'];
        
        // Skip if duplicate email
        if (isset($processed_users[$email])) {
            continue;
        }
        
        // Skip if inactive (not logged in for 30+ days)
        if ($user['last_login'] < $cutoff_date) {
            continue;
        }
        
        // Add display_name field
        $user['display_name'] = $user['name'] . ' (' . ucfirst($user['role']) . ')';
        
        // Add to processed array using email as key for uniqueness
        $processed_users[$email] = $user;
    }
    
    // Step 3: Define role priorities for sorting
    $role_priority = [
        'admin' => 1,
        'editor' => 2,
        'author' => 3,
        'subscriber' => 4
    ];
    
    // Step 4: Sort by role priority
    uasort($processed_users, function($a, $b) use ($role_priority) {
        $priority_a = isset($role_priority[$a['role']]) ? $role_priority[$a['role']] : 999;
        $priority_b = isset($role_priority[$b['role']]) ? $role_priority[$b['role']] : 999;
        
        return $priority_a <=> $priority_b; // Using spaceship operator (PHP 7+)
    });
    
    // Step 5: Reset array keys and return
    return array_values($processed_users);
}

// Example usage:
$user_records = [
    [
        "name" => "John Doe",
        "email" => "john@example.com",
        "role" => "editor",
        "last_login" => "2023-05-10"
    ],
    [
        "name" => "Jane Smith",
        "email" => "jane@example.com",
        "role" => "admin",
        "last_login" => "2023-05-20"
    ],
    [
        "name" => "Bob Johnson",
        "email" => "bob@example.com",
        "role" => "subscriber",
        "last_login" => "2023-04-15" // Inactive (more than 30 days ago)
    ],
    [
        "name" => "Alice Brown",
        "email" => "alice@example.com",
        "role" => "author",
        "last_login" => "2023-05-18"
    ],
    [
        "name" => "John Duplicate",
        "email" => "john@example.com", // Duplicate email
        "role" => "author",
        "last_login" => "2023-05-22"
    ]
];

$dashboard_users = process_users_for_dashboard($user_records);
print_r($dashboard_users);

Step 4: Review and Improve

Let's review our solution and consider improvements:

  • Correctness: The solution correctly implements all the requirements - removing duplicates, filtering inactive users, sorting by role, and adding display names.
  • Efficiency: By using email as the key in our intermediate array, we efficiently remove duplicates without needing an extra loop.
  • Readability: The code is well-structured with comments explaining each step.

Possible improvements:

  1. Add error handling for malformed input
  2. Make the inactive cutoff period configurable
  3. Add more sophisticated sorting (e.g., by role first, then by name)

Here's an improved version with these enhancements:

/**
 * Process user records for dashboard display with enhanced features
 * 
 * @param array $users Array of user records
 * @param int $inactive_days Days to consider a user inactive
 * @param array $custom_priorities Custom role priority mapping
 * @return array Processed user records
 */
function process_users_for_dashboard_enhanced($users, $inactive_days = 30, $custom_priorities = []) {
    // Validate input
    if (!is_array($users)) {
        return [];
    }
    
    // Initialize variables
    $processed_users = [];
    $cutoff_date = date('Y-m-d', strtotime("-$inactive_days days"));
    
    // Define default role priorities
    $default_priorities = [
        'admin' => 1,
        'editor' => 2,
        'author' => 3,
        'contributor' => 4,
        'subscriber' => 5
    ];
    
    // Merge with custom priorities if provided
    $role_priority = array_merge($default_priorities, $custom_priorities);
    
    // Process each user
    foreach ($users as $user) {
        // Validate user record
        if (!isset($user['email']) || !isset($user['name']) || 
            !isset($user['role']) || !isset($user['last_login'])) {
            continue; // Skip invalid records
        }
        
        $email = $user['email'];
        
        // Skip if duplicate email (keep the one with the most recent login)
        if (isset($processed_users[$email])) {
            // If this login is more recent, replace the existing record
            if ($user['last_login'] > $processed_users[$email]['last_login']) {
                // Keep processing this user
            } else {
                continue; // Skip this user
            }
        }
        
        // Skip if inactive
        if ($user['last_login'] < $cutoff_date) {
            continue;
        }
        
        // Format the last_login date for display
        $user['formatted_login'] = date('F j, Y', strtotime($user['last_login']));
        
        // Add display_name field
        $user['display_name'] = $user['name'] . ' (' . ucfirst($user['role']) . ')';
        
        // Add to processed array using email as key for uniqueness
        $processed_users[$email] = $user;
    }
    
    // First sort by role priority, then by name
    uasort($processed_users, function($a, $b) use ($role_priority) {
        // Get role priorities
        $priority_a = isset($role_priority[$a['role']]) ? $role_priority[$a['role']] : 999;
        $priority_b = isset($role_priority[$b['role']]) ? $role_priority[$b['role']] : 999;
        
        // If roles are different, sort by role priority
        if ($priority_a !== $priority_b) {
            return $priority_a <=> $priority_b;
        }
        
        // If roles are the same, sort by name
        return strcmp($a['name'], $b['name']);
    });
    
    // Reset array keys and return
    return array_values($processed_users);
}

This enhanced version offers more flexibility and better handles edge cases while maintaining the core functionality of the original solution.

Real-World Applications in WordPress

Understanding array functions is crucial for WordPress development. Here are some common scenarios where you'll use these techniques:

Processing Custom Post Types

/**
 * Get and process featured products for a homepage carousel
 */
function get_featured_products() {
    // Get raw product posts
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'meta_query' => array(
            array(
                'key' => '_featured',
                'value' => 'yes',
                'compare' => '='
            )
        )
    );
    
    $products = get_posts($args);
    
    // Transform into a simpler format for the carousel
    $featured_products = array_map(function($product) {
        // Get product data
        $product_id = $product->ID;
        $thumbnail = get_the_post_thumbnail_url($product_id, 'medium');
        $price = get_post_meta($product_id, '_price', true);
        
        // Build the featured product array
        return array(
            'id' => $product_id,
            'title' => get_the_title($product),
            'image' => $thumbnail ? $thumbnail : '/images/placeholder.jpg',
            'price' => $price ? '$' . number_format($price, 2) : 'Price unavailable',
            'url' => get_permalink($product)
        );
    }, $products);
    
    // Sort by price (lowest first)
    usort($featured_products, function($a, $b) {
        $price_a = str_replace(['$', ','], '', $a['price']);
        $price_b = str_replace(['$', ','], '', $b['price']);
        
        // Handle non-numeric prices
        if (!is_numeric($price_a)) return 1;
        if (!is_numeric($price_b)) return -1;
        
        return $price_a <=> $price_b;
    });
    
    // Limit to 5 products
    return array_slice($featured_products, 0, 5);
}

Working with WordPress Settings

/**
 * Merge default plugin settings with user settings
 */
function get_plugin_settings() {
    // Default settings
    $defaults = array(
        'enable_feature_a' => true,
        'enable_feature_b' => false,
        'max_items' => 10,
        'display_mode' => 'grid',
        'cache_time' => 3600
    );
    
    // Get user settings
    $user_settings = get_option('my_plugin_settings', array());
    
    // Merge defaults with user settings
    $settings = array_merge($defaults, $user_settings);
    
    return $settings;
}

/**
 * Validate and sanitize plugin settings
 */
function sanitize_plugin_settings($input) {
    $valid_settings = array();
    
    // Define allowed settings and their types
    $allowed_settings = array(
        'enable_feature_a' => 'boolean',
        'enable_feature_b' => 'boolean',
        'max_items' => 'integer',
        'display_mode' => 'string',
        'cache_time' => 'integer'
    );
    
    // Process each input
    foreach ($input as $key => $value) {
        // Skip if not an allowed setting
        if (!array_key_exists($key, $allowed_settings)) {
            continue;
        }
        
        // Sanitize based on expected type
        switch ($allowed_settings[$key]) {
            case 'boolean':
                $valid_settings[$key] = (bool) $value;
                break;
                
            case 'integer':
                $valid_settings[$key] = intval($value);
                break;
                
            case 'string':
                $valid_settings[$key] = sanitize_text_field($value);
                break;
        }
    }
    
    return $valid_settings;
}

Processing Form Data

/**
 * Process a multi-checkbox form field
 */
function process_form_checkboxes() {
    // No checkboxes were checked
    if (!isset($_POST['interests'])) {
        return array();
    }
    
    // Get submitted interests
    $submitted_interests = $_POST['interests'];
    
    // Make sure it's an array
    if (!is_array($submitted_interests)) {
        $submitted_interests = array($submitted_interests);
    }
    
    // Define allowed values
    $allowed_interests = array('sports', 'music', 'movies', 'books', 'travel');
    
    // Filter out invalid values
    $valid_interests = array_filter($submitted_interests, function($interest) use ($allowed_interests) {
        return in_array($interest, $allowed_interests);
    });
    
    // Sanitize each value
    $sanitized_interests = array_map('sanitize_text_field', $valid_interests);
    
    return $sanitized_interests;
}

Homework Assignment: Array Function Practice

Create a PHP function that takes a list of products (as an array) and transforms it for a WordPress theme's featured products section. The function should accomplish the following:

  1. Accept an array of products, each containing 'id', 'name', 'category', 'price', and 'stock' fields
  2. Remove out-of-stock products (stock = 0)
  3. Group products by category
  4. Sort products within each category by price (lowest first)
  5. Format prices to display with a currency symbol and two decimal places
  6. Limit each category to show a maximum of 3 products
  7. Return the processed array

Starter code:

/**
 * Process products for featured products section
 * 
 * @param array $products Array of product records
 * @return array Processed products grouped by category
 */
function process_featured_products($products) {
    // Your solution here
}

// Sample data to test your function
$products = [
    [
        'id' => 101,
        'name' => 'Wireless Headphones',
        'category' => 'Electronics',
        'price' => 59.99,
        'stock' => 15
    ],
    [
        'id' => 102,
        'name' => 'Bluetooth Speaker',
        'category' => 'Electronics',
        'price' => 89.99,
        'stock' => 0 // Out of stock
    ],
    [
        'id' => 103,
        'name' => 'Smartphone Case',
        'category' => 'Accessories',
        'price' => 19.99,
        'stock' => 32
    ],
    [
        'id' => 104,
        'name' => 'Laptop Sleeve',
        'category' => 'Accessories',
        'price' => 29.99,
        'stock' => 8
    ],
    [
        'id' => 105,
        'name' => 'Wireless Charger',
        'category' => 'Electronics',
        'price' => 34.99,
        'stock' => 12
    ],
    [
        'id' => 106,
        'name' => 'Smartwatch',
        'category' => 'Electronics',
        'price' => 199.99,
        'stock' => 5
    ],
    [
        'id' => 107,
        'name' => 'Phone Mount',
        'category' => 'Accessories',
        'price' => 14.99,
        'stock' => 21
    ],
    [
        'id' => 108,
        'name' => 'Tablet Stand',
        'category' => 'Accessories',
        'price' => 24.99,
        'stock' => 0 // Out of stock
    ]
];

$featured = process_featured_products($products);
print_r($featured);

Use the array functions we've covered in this lesson to create an elegant solution. Try to use at least 5 different array functions in your implementation.

Further Learning

Coming Up Next

In our next session, we'll explore PHP array sorting techniques, learning how to organize and arrange array data for optimal presentation and processing.