Drop elements from a array based on another array - php

$arr1 = array(
'a' => 123,
'b' => 123,
'c' => 123,
'd' => 123,
);
$arr2 = ('a', 'b', 'c', 'd', 'e');
How can I remove elements from $arr2 that don't exist as keys in $arr1 ?
for example e doesn't exist as key in $arr1 so it should be removed

$arr2 = array_intersect($arr2, array_keys($arr1))
it computes intersection of two sets - $arr2 values and $arr1 keys

Try this:
foreach ( $arr2 as $key => $value ) {
if ( !array_key_exists( $value, $arr1 ) ) {
unset( $arr2[$key] );
}
}

Why not use the simple approach and use array_keys? This avoids having to perform an operation for each key by getting ALL of the keys at once.
$arr2 = array_keys($arr1);

Related

comapring two arrays and return the index of the common element in php

i have two arrays in php and i am using the array_intersect function to find the common elements and if common elements exists i want to display the index of theses common elements in the 1st array
here is what i have done so far..
function check_if_exists($company_timings,$in_time)
{
$length_of_company=sizeof($company_timings);
$length_of_emp=sizeof($in_time);
$common=array_intersect($company_timings,$in_time);
$length_of_common=sizeof($common);
$key=array_search($common,$company_timings);
return $key;
}
but its not return the keys there are common elements which are 09:00:00 and 11:00:00 and when i pass 11:00:00 rather than $common in array_search then it gives the accurate result other wise with the $common_array it doesn't work,,,kindly help me in ameliorating the code
This function returns an array containing the common elements and their positions in both array, or falseif no common elements are found :
function check_if_exists($arr1, $arr2) {
$combined = array_intersect($arr1, $arr2);
if (empty($combined))
return false;
$return = array();
foreach ($combined as $elmt) {
$return[$elmt] = array();
$return[$elmt]['arr1'] = array_search($elmt, $arr1);
$return[$elmt]['arr2'] = array_search($elmt, $arr2);
}
return $return;
}
Test :
$array1 = array('a', 'b', 'c', 'd');
$array2 = array('b', 'f', 'g', 'c');
$array3 = array('n', 'o', 'p', 'e');
$exists = check_if_exists($array1, $array2);
var_dump($exists);
$exists_no = check_if_exists($array1, $array3);
var_dump($exists_no);
Output :
array (size=2)
'b' =>
array (size=2)
'arr1' => int 1
'arr2' => int 0
'c' =>
array (size=2)
'arr1' => int 2
'arr2' => int 3
boolean false
Try with array_keys function
Here is an example code. Hope it will help you.
<?php
$a = array("a","b","c");
$b = array("c","d","a");
$c = array_keys(array_intersect($a,$b));
var_dump($c);
?>

Issue with array_combine()

I have two arrays. The one's array key is another's value. Here is code:
$arr1 = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'pear',
);
$arr2 = array(
'bird' => 'a',
'dog' => 'b',
);
And my question, how to combine two arrays in one like:
$arr3 = array(
'bird' => 'apple',
'dog' => 'banana',
);
Is there have some array function to do this probably?
<?php
$arr3 = array();
foreach ($arr2 as $item => $value) {
$arr3[$item] = $arr1[$value];
}
print_r($arr3);
something along those lines anyway.
If you literally want to merge the arrays, array_merge will do the job fine.
Edit: This is a fun way and matches the keys:
$arr3 = array_combine(array_intersect_key($k = array_flip($arr2), $arr1),
array_intersect_key($arr1, $k));
Original with no key matching:
Here's a way. Doesn't matter which array is longer:
$arr3 = array_combine(array_slice(array_keys($arr2), 0, count($arr1)),
array_slice($arr1, 0, count($arr2)));

Create indexed array of two-element subarrays from flat associative array

Is it possible to convert this array:
array(
'A' => 'B',
'C' => 'D',
)
To this array:
array(
array(
'A',
'B',
),
array(
'C',
'D',
),
)
You are probably looking for the array_map (builds pairings based on existing arrays, see Example #4 Creating an array of arrays on the manual page) and the array_keys (all keys of an array) functions:
array_map(null, array_keys($array), $array));
$source = array(
'A' => 'B',
'C' => 'D',
)
foreach ($source as $key => $value){
$result[] = array($key, $value);
}
var_dump($result);

Select 2 random elements from associative array

So I have an associative array and I want to return 2 random values from it.
This code only returns 1 array value, which is any of the 4 numbers at random.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$key = array_rand($array); //array_rand($array,2); Putting 2 returns Illegal offset type
$value = $array[$key];
print_r($value); //prints a single random value (ex. 3)
How can I return 2 comma separated values from the array values only? Something like 3,4?
array_rand takes an additional optional parameter which specifies how many random entries you want out of the array.
$input_array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$rand_keys = array_rand($input_array, 2);
echo $input_array[$rand_keys[0]] . ',' . $input_array[$rand_keys[1]];
Check the PHP documentation for array_rand here.
Grab the keys from the array with array_keys(), shuffle the keys with shuffle(), and print out the values corresponding to the first two keys in the shuffled keys array, like so:
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$keys = array_keys( $array);
shuffle( $keys);
echo $array[ $keys[0] ] . ',' . $array[ $keys[1] ];
Demo
Or, you can use array_rand()'s second parameter to grab two keys, like so:
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$keys = array_rand( $array, 2);
echo $array[ $keys[0] ] . ',' . $array[ $keys[1] ];
Demo
There is a more efficient approach that preserves keys and values.
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
Check the documentation here
$a=rand(0,sizeof($array));
$b=$a;
while ($a==$b) $b=rand(0,sizeof($array));
$ar=array_values($array);
$element1=$ar[$a];
$element2=$ar[$b];
Should be more efficient than shuffle() and freinds, if the array is large.

php. array_values function. how to get mapping from old keys to new keys?

There is function array_values in PHP such that
$array2 = array_values($array1);
$array2 has the same values as $array1 but keys are from
0 to sizeof($array1) - 1. Is it possible to get mapping from old keys to new keys?
EDIT. I will explain on an example:
$array1 = array( 'a' => 'val1', 'b' => 'val1');
$array2 = array_values( $array1 );
so now array2 has next values
$array2[0] = 'val1'
$array2[1] = 'val2'
How get array3 such that:
$array3['a'] = 0
$array3['b'] = 1
To produce a key map you need to first get the keys into a regular array and then flip the keys and values:
$array1_keymap = array_flip(array_keys($array1));
For example:
$array1 = array(
'a' => 123,
'b' => 567,
);
$array1_values = array_values($array1);
$array1_keymap = array_flip(array_keys($array1));
Value of $array1_values:
array(
0 => 123,
1 => 567,
);
Value of $array1_keymap:
array(
'a' => 0,
'b' => 1,
);
So:
$array1['a'] == $array1_values[$array1_keymap['a']];
$array1['b'] == $array1_values[$array1_keymap['b']];
Yes, as simple as
$array2 = $array1;
In this case you would get both values and keys like they are in the original array.
$keyMapping = array_combine(array_keys($array1), array_keys($array2));
This the keys of $array1 and maps them to the keys of $array2 like so
<?php
$array1 = array(
'a' => '1',
'b' => '2',
);
$array2 = array_values($array1);
print_r(array_combine(array_keys($array1), array_keys($array2)));
Array
(
[a] => 0
[b] => 1
)
You can use:
$array3 = array_keys($array1);
Now $array3[$n] is the key of the value in $array2[$n] for any 0 <= $n < count($array1). You can use this to determine which keys were in which places.
If you want to keep the same value of array1 but change the key to index numbers, try this:
$array2 = array();
foreach ($array1 as $key => $value){
$array2[] = $value;
// or array_push($array2, $value);
}
var_dump($array2);

Categories