How to relate 2 arrays (array1 is name and array2 is ID) and bring the corresponding value

Asked

Viewed 111 times

0

I have 2 arrays, where one is an array with the names and the other is an array with the ids. I need that according to the name of the string (which it contains in the $name array), it searches in the id array, the corresponding id, eg:

$nome=array('a','b','c');
$id=array('1','2','3');
$caracnome='b';

There I need, in this example, to bring for example the variable $caracid = '2', because 'b' is the second value of the $name array and the second value of the $id array is 2.

1 answer

1


You have the function array_combine php combining one array with another causing the first array to be the keys and the second the values. For your code to associate the two things allows you to easily know which id is associated with a given name.

Use the array_combine would be so:

$nomesIds = array_combine($nome, $id);

What’s left in this $nomesIds is:

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

So to get the id of b suffice:

$caracid = $nomesIds[$caracnome];

See the example in Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.