Current Location: Home> Latest Articles> Typical Use Cases of PHP array_values Combined with array_map

Typical Use Cases of PHP array_values Combined with array_map

gitbox 2025-06-11

Example 1: Extracting and Formatting Values from an Associative Array

In development, you often work with associative arrays like ['name' => 'Tom', 'age' => 28]. If you're only interested in the values and want them all as strings:

$data = ['name' => 'Tom', 'age' => 28];
<p>$formatted = array_map('strval', array_values($data));</p>
<p>print_r($formatted);<br>

Output:

Array
(
    [0] => Tom
    [1] => 28
)

In this case, array_values() strips the keys, and array_map() converts the values to strings.


Example 2: Cleaning Array Values and Reindexing

Imagine receiving user input as the following array, which includes extra spaces and inconsistent formats:

$input = [
    'first' => ' Alice ',
    'second' => 'BOB',
    'third' => ' charlie '
];

You want to trim whitespace, convert to lowercase, and rebuild a reindexed array:

$clean = array_map('trim', array_map('strtolower', array_values($input)));
<p>print_r($clean);<br>

Output:

Array
(
    [0] => alice
    [1] => bob
    [2] => charlie
)

This nested use of array_map() processes each value, and array_values() reindexes the array, resulting in a clean and simple output.


Example 3: Extracting Object Properties or Array Keys in Bulk

When working with an array of objects or associative arrays, it's common to extract a specific field — like user IDs in this case:

$users = [
    ['id' => 101, 'name' => 'Lily'],
    ['id' => 102, 'name' => 'John'],
    ['id' => 103, 'name' => 'Mike']
];
<p>$ids = array_values(array_map(function ($user) {<br>
return $user['id'];<br>
}, $users));</p>
<p>print_r($ids);<br>

Output:

Array
(
    [0] => 101
    [1] => 102
    [2] => 103
)

Here, array_map() pulls out the key value, and array_values() ensures a clean, sequential index — perfect for data processing or frontend JSON output.


Example 4: Generating URL Paths in Bulk

Sometimes you need to generate parameterized URLs based on data fields — for instance, creating profile page paths from usernames:

$names = ['alice', 'bob', 'charlie'];
<p>$urls = array_map(function ($name) {<br>
return '<a rel="noopener" target="_new" class="" href="https://gitbox.net/user/profile/">https://gitbox.net/user/profile/</a>' . urlencode($name);<br>
}, array_values($names));</p>
<p>print_r($urls);<br>

Output:

Array
(
    [0] => https://gitbox.net/user/profile/alice
    [1] => https://gitbox.net/user/profile/bob
    [2] => https://gitbox.net/user/profile/charlie
)

array_map() builds the path strings, while array_values() ensures a sequential index array — ideal for JSON responses or frontend integration.