Simplify finding values ​​in arrays in PHP

Question:

I have the arrays as below:

$records = [
    ["id"=>"1", "name"=>"Alpha"],
    ["id"=>"2", "name"=>"Bravo"],
    ["id"=>"3", "name"=>"Charlie"],
    ["id"=>"4", "name"=>"Delta"],
    ["id"=>"5", "name"=>"Echo"],
];

$codes = [2,4];

I need to print only the names contained in the variable $records corresponding to each code of the variable $codes waiting for the result:

angry

Delta

So I made the following code:

foreach ($codes as $i) {
    foreach ($records as $j) {
        if ($i == $j['id']) {
            echo "<p> {$j['name']} </p>";
        }
    }
}

Is there any way to get the same result easier?

I think it's bad the way I'm doing because for each code of the variable $codes I do a full scan on the variable $records comparing the values.

Answer:

Since the id value is unique for each name, you can define a map that relates the id to the respective name. In PHP, we can define this map through an associative array where the key is the id and the value is its name. We can build this map with a line of code:

$nomes = array_column($records, "name", "id");

This will generate the array :

Array
(
    [1] => Alpha
    [2] => Bravo
    [3] => Charlie
    [4] => Delta
    [5] => Echo
)

Thus, it would be enough to access the positions $nomes[2] and $nomes[4] , or:

foreach ($codes as $code) {
    echo $nomes[$code], PHP_EOL;
}

Displaying the desired names.

Scroll to Top