简体   繁体   中英

PHP delete array value

I have 2 arrays.

<?php
$array1 = array('id' => 1, 'email' => 'example@example.com' , 'name' => 'john' );
$array2 = array('id', 'email');

i am having trouble writing a code to unset the key value pair from array1 that is not from array 2.

The problem with this is unlike most examples, my array2 does not have a format of a key value pair but only key.

How do i go about removing things from array1 that is not specified in array2.

my current code is not working

foreach ($array1 as $key => $value) {
if (array_search($key, $array2)===false) {
 unset($key);
}
}

Use array_diff_key() to leave values which are not in second array:

$array1 = array('id'=>1, 'email'=> 'email' , 'name'=>'john' );
$array2 = array('id','email');

$result = array_diff_key($array1, array_flip($array2));

Or, if you want to change first array:

$array1 = array_diff_key($array1, array_flip($array2));

Edit (misunderstanding)

Use array_intersect_key() to leave values which are in second array:

$array1 = array_intersect_key($array1, array_flip($array2));

You are doing it right, just that your way of unset is incorrect:

unset($key);

should be

unset($array1[$key]);

Demo

You have to unset the element by its index (starting from 0) For example unset($array2[1]); will remove the 'email' element.

So in Your case it should be: unset($array1[$key]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM