# 5 PHP array functions that make data manipulation easier

After working across projects involving dataset processing, I've had to clean up and compare data from different collections. Working with these collections might require extracting a dataset into a structured array. I had to make use of several functions at various points to achieve this, but a few really caught my attention.

Here are the 5 functions I've used while building the Potsandfeelings recommendation system with real-world examples.

1. array_filter():

Let's say you have a product catalogue array. This contains product_name, product_instock, and you want to extract only products that are in stock. Using array_filter(), you can filter the array for products whose product_instock is set to true.

```php
$availableProducts = array_filter(
    $products,
    fn ($product) => $product['product_instock'] === true
);
```

This checks existing products in an array and runs a callback check on each of the products. If a product doesn't pass the check, it is excluded from the array. This can be used for any implementation that requires filtering, such as job filtering or rank-based filtering.

I used this particularly in Potsandfeelings when filtering meals based on a country. For a meal recommendation system based on location / mood, one of the first things to do is extract meals associated with that location. A request from a particular location should only continue with the matching country record.

```php
array_filter($countries, fn ($c) => is_array($c) &&
    ($this->key($c['country'] ?? '') === $countryKey ||
     $this->key($c['code'] ?? '') === $countryKey)
);
```

This runs checks using the country name (country) and the country code (code) to identify and extract the required list.

This process helps because it reduces large collections to more relevant results one can work with.

2. array_map():

array_map() basically helps in transforming each element of an array without disrupting the list itself. array_filter() detects what should be output from an array. array_map() transforms array elements to be output.

For instance, it's very useful in a scenario where you want to convert all items in an array into lowercase.

Converting data in an array into lowercase is important especially when you need consistent data names during development. Items named "Nike shoe" and "NIKE SHOE" could be read differently.

```php
$products = array_map(
    fn ($products_list) => strtolower(trim($products_list['name'])),
    $products_list
);
```

This outputs a new array list with product names trimmed and converted to lowercase.

In Potsandfeelings, I needed a consistent naming structure for meal names between different dataset collections. Differences in extra spaces or capitalization shouldn't cause a valid meal to be rejected.

```php
$names = array_map($this->key(...), $mealNames);
```

Here, array_map is used to apply the custom key() method to every meal name.

```php
private function key(string $value): string
{
    return mb_strtolower(
        preg_replace('/\s+/u', ' ', trim($value)),
        'UTF-8'
    );
} 
```

This key method collapses repeated whitespace, trims surrounding whitespace and also converts each meal name to lowercase. This gives me a consistent meal name pattern to work with.

3. array_intersect():

This finds matching values shared between 2 or more arrays. This can be useful in an instance where you are building a job search portal and you need to match recruiters’ requirement lists with candidates’ skills lists.

```php
$candidateSkills = ['PHP', 'Laravel', 'MySQL'];
$requiredSkills = ['Laravel', 'MySQL', 'Docker'];

$matchingSkills = array_intersect(
    $candidateSkills,
    $requiredSkills
);
```

This outputs Laravel and MySQL. Now, with this, you can grade how well candidates fit the required skills for a job.

During the Potsandfeelings recommendation process, once I had eligible recipes based on the user’s location, I had to compare each recipe's mood associations with the user's desired mood.

```php
$score = count(
    array_intersect($goals, $recipe['mood_associations'])
);
```

With this example, if a user picks cozy and comforted, a recipe carrying both scores 2. A recipe carrying only 'cozy' scores 1. This further narrows down the meal list for recommendation.

4. array_column():

Suppose you want to extract the order amounts from an array of orders and calculate the total.

```php
$orders = [
    ['id' => 101, 'amount' => 5000],
    ['id' => 102, 'amount' => 5000],
    ['id' => 103, 'amount' => 3000],
];

$amounts = array_column($orders, 'amount');
```

This would output:

```php
[5000, 5000, 3000]
```

Therefore, you can now do something like this:

```php
$total = array_sum($amounts);
```

Also, array_column() can accept a third argument: the index key. For instance, you can extract amounts into a new array with IDs as keys.

```php
$amountsByOrder = array_column($orders, 'amount', 'id');
```

After using array_intersect() in Potsandfeelings to get recipes and scores, I had to find the meal with the highest score. This would be the meal most suited for recommendation.

```php
$bestScore = max(array_column($candidates, 'score'));
```

array_column() pulls scores into a separate array and max() finds the highest score.

This algorithm filters meal candidates again, keeping the meals with the highest score.

5. random_int():

Although random_int() is not an array function, it is very useful in selecting an item from an array. Its use is vast and underrated.

I used random_int() to select a meal when recipes shared the highest matching score.

Earlier, array_intersect() helped score the recipes by comparing mood associations. After getting the highest-scoring meals, I still needed to pick one.

```php
$recipe = $best[
    random_int(0, count($best) - 1)
]['recipe'];
```

Order is important. Random selection happens after the candidate meals have passed filtering and ranking.

Working with arrays becomes easier when you understand the role each function plays. This has helped when it comes to filtering, comparing, extracting and identifying data.
