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 false
if 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);
?>