0

Suppose I have first array, $aAllCities as

Array
(
   [21] => London
   [9]  => Paris
   [17] => New York
   [3]  => Tokyo
   [25] => Shanghai
   [11] => Dubai
   [37] => Mumbai
)

And another array, $aNotSupportedCities as

Array
(
   [0] => 37
   [1] => 25
   [2] => 11
)

Is it possible to get an array like this ?

Array
(
   [21] => London
   [9]  => Paris
   [17] => New York
   [3]  => Tokyo
)

I want to remove array values of those keys that are present in other array

5 Answers 5

2

Try this:

$aAllCities = array_flip( $aAllCities );
$aAllCities = array_diff( $aAllCities, $aNotSupportedCities );
$aAllCities = array_flip( $aAllCities );

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Pushpesh, exactly what I wanted
2
foreach($aAllCities as $key => $value) {
    if(in_array($key,$aNotSupportedCities)) {
        unset($aAllCities[$key]); 
    }

}

Comments

2

The other answers are correct, but a smoother, faster way to do it is:
$supportedCities = array_diff_key($aAllCities, $aNotSupportedCities);

This will return all the values from $aAllCities that don't have keys in $aNotSupportedCities

Note, this compares the two arrays via their keys, so you will need to make your $aNotSupportedCities look like this:

Array
(
   [37] => something
   [25] => doesn't really matter
   [11] => It's not reading this
)

Best of luck.

Comments

1
$supportedCities = array_diff_key($aAllCities, array_values($aNotSupportedCities));

Comments

0
$new = $aAllCities;
foreach($aNotSupportedCities as $id) {
  if (isset($new[$id]) {
    unset($new[$id]);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.