Nick T Nick T - 1 day ago 4
PHP Question

PHP 2 arrays using one to chose from the other

I am new to php and my problem is i have 2 arrays the first one is from another page via post and read into an array via post_get

Array (

[0] => 93
[1] => 25
[2] => 5
[3] => 4
[4] => 36
)


and my second array looks like this

Array (

[25] => Estonia
[20] => France
[4] => Germany
[5] => Greece
[75] => Hungary
[93] => India
[36] => Italy
)


what i want to do is if the array looks like the first one then it uses the numbers from the array and with the help from the second array makes a new array that only contains

Array (

[0] => India
[1] => Estonia
[2] => Greece
[3] => Germany
[4] => Italy

)


and using this doesn't work

$group is the first array
$array is the one with the country names

foreach ($group as $value) {
if (in_array($value, $array)) {
}
else {
echo "The group ".$value." does not exist";

}
}

Answer

You can do this many ways. Here is a simple one:

$new = [];
foreach ($group as $groupId) {
    if (isset($array[$groupId])) {
        $new[] = $array[$groupId];
    }
}
Comments