Any function to get elements in common in two arrays? - php

Is there any function that does the inverse operation of array_diff()?
I mean, if i have:
array(1,2,3)
array(3,4,5)
I would like that function returns array(3), or directly 3.
Note: array_intersect() doesn't fit me.
Javier

If array_intersect() doesn't fit me is because it returns:
Array
(
[2] => 3
)
and not:
Array
(
[0] => 3
)
or
3
Then you could easily transform the array to something workable with array_values():
<?php
$arr1 = array(1,2,3);
$arr2 = array(3,4,5);
$new = array_values(array_intersect($arr1,$arr2));
$new = $new[0];
print_r($new); //3
?>
Else please explain your situation.

Try array_intersect() this will computes the intersection of arrays

Since you don't want to use array_intersect(), check this inefficient method:
$arr1= array(1,2,3);
$arr2= array(3,4,5);
function arr_intersect($array1, $array2)
{
$array_result=array();
$array_shared = array_diff($array1+$array2, array_diff($array1, $array2));
$count=count($array_shared);
return array_values($array_shared);
}
print_r(arr_intersect($arr1, $arr2));

Related

associative array in sort using php

$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
Array
(
[0] => 5
[1] => 4
[2] => 1
[3] => 2
)
Expecting result
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 5
)
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
$results = [];
foreach($array as $key=>$value){
$results[$key] = arsort($value);
}
echo "<pre>";
print_r($results);
Please suggest how do we can sort associative array i did try but does not work for me please guide
As per your "expected results' it seems like you don't wish to maintain the keys. If that's the case then you can just use sort.
Something like this..
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
sort($array);
print_r($array);
Just do
sort($array);
Also check the PHP documentation if you need further customization: http://php.net/manual/en/function.sort.php
var_dump( array_reverse($array,false));
you don't need to use foreach or sort ,you can just use array_reverseinstead ,avery simple way
You don't need to iterate using foreach for sorting
Just use sort for sorting array
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
sort($array);
print_r($array);
This will not maintain array keys and if you want arrays keys to be same just replace sort with asort in above code

Sorting Array [0]

Array ( [0] => wilson )
Array ( [0] => umkk )
Array ( [0] => audiok )
Array ( [0] => Futurama )
I have the above users array, i'm trying to sort it alphabetically so the result looks like this
audiok
futurama
umkk
wilson
This is my php code from those lines:
$arr1 = explode("\n", $users);
sort ($arr1);
print_r($arr1);
Why isn't sort () working? It doesnt sort it at all.. what am i doing wrong? I'm new to php programming, i have looked on the php manual and have not been able to sort it after trying all these different examples posted there.
Thanks in advanced.
Edit:
preg_match_all('/control\?user=(.+?)&data/', $linklong, $users)
$users = $users[1][0];}
if i print $users all the users are displayed nicely, but when i tried to sort them it tells me is not array, so i took $users, and did explode to create the array... i'm sorry im not very programming savy –
<?php
$array1 = array(0=>'wilson');
$array2 = array(0=>'umkk');
$array3 = array(0=>'audiok');
$array4 = array(0=>'Futurama');
$array = array_merge($array1,$array2,$array3,$array4);
natcasesort($array);
echo '<pre>',print_r($array),'</pre>';
Or if you have text that is 4 names on 4 different lines that you want to explode and sort:
<?php
$text = <<<EOD
wilson
umkk
audiok
Futurama
EOD;
$arr = explode("\n",$text);
natcasesort($arr);
echo '<pre>',print_r($arr),'</pre>';
natcasesort() docs
asort() is the function that u need. Following URL contains the example and the output.
http://www.php.net/manual/en/function.asort.php

PHP 2 arrays - merge values existing in both arrays to one array

I have 2 arrays:
$array1 = array(1,2,3,4,5);
$array2 = array(3,4,5,6,7);
Is there any PHP function that does this?
$finalArray = unknown_php_function($array1,$array2);
// result: $finalArray = array(3,4,5);
It merges both arrays and removes values which aren't present in both arrays. Do I have to build a foreach cycle or is there an easier way? Thanks
You want array_intersect for this, basically the intersection of two sets (arrays, in this case), just like in school. :-)
You're looking for array_intersect(). Here is a demo:
$array1 = array(1,2,3,4,5);
$array2 = array(3,4,5,6,7);
$finalArray = array_intersect($array1,$array2);
print_r($finalArray);
Outputs:
Array
(
[2] => 3
[3] => 4
[4] => 5
)

Array_unshift like function that returns the array

is there a built in function in php that prepends an element to an array, and returns the new array?
instead of returning the new length of the array?
You could use
array_merge()
For example
$resultingArray = array_merge(array($newElement), $originalArray);
Next to array_merge, if there ain't any duplicate keys, you can do:
$array = array('a' => 'A');
$append = array('b' => 'hello');
$array = $append + $array;
Gives:
Array
(
[b] => hello
[a] => A
)
The plus is the array union operator­Docs.
There's no built-in which does it, but it's simple enough to wrap it:
function my_unshift($array, $var) {
array_unshift($array, $var);
return $array;
}
This isn't necessary though, because array_unshift() operates on an array reference so the original is modified in place. array_push(), array_pop(), array_shift() all also operate on a a reference.
$arr = array(1,2,3);
array_unshift($arr, 0);
// No need for return. $arr has been modified
print_arr($arr);
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)

How to compare arrays and extract the difference?

I have two arrays that I would like to compare and ultimately wind up with a single array with everything combined, having no duplicates. Can someone please tell me which function I should use? There are so many that it's a bit confusing.
$array1[]['name'] = 'Kim, Jones';
$array1[]['name'] = 'Jim, Miller';
array1 is an array I built that I want added to an array coming from the database. The key in the second array is also named "name". Thanks.
EDIT:
I managed to merge these two arrays but I can still see duplicates.
This is what the first array looks like:
Array
(
[0] => Array
(
[WNumber] => ADMIN
[Name] => Tim, Cooley
[Employer] => CalPERS
[Student] => 1
[Perm] => 1
[QA] => 0
[Supervisor] => 1
[RQW] => 0
)
My second array is built like this:
$add_names[]['Name']='Jim, Jones';
I just want to add $add_names to the first array WHERE there are no duplicates.
I'm tempted to sell you on CakePHP, since it has a number of functions that makes this easy in its "Set" class. Your problem is that you have the results in a nested array. A simple "array_unique" does not work in a nested array.
I'd do it the old fashioned way...
$array1[]['name'] = 'Kim, Jones';
$array1[]['name'] = 'Jim, Miller';
$array2[]['name'] = 'Kim, Jones';
$array2[]['name'] = 'Jimbo, Miller';
$array2[]['name'] = 'Jim, Jones';
$new_array=array_merge($array1, $array2);
$out_array = array();
$key_array = array();
foreach($new_array as $i => $row) {
if (empty($key_array[$row['name']])) {
$out_array[] = $row;
}
$key_array[$row['name']] = 1;
}
print_r($out_array);
This code works for me...
I think you'll need to use a combination of array_merge (adds the two arrays together) and array_unique (removes duplicate values).
$resulting_array = array_unique(array_merge($array1, $array2));
Note that array_unique will not work correctly when using multi-dimensional arrays, so if your array data looks the way you put it in your question, you'll have to think of a way around that. One of the comments on the array_unique page suggests serialize'ing all array values before running array_unique on it. Afterwards you'd just run unserialize on all array elements. Note that this can mean a performance hit if you have a big array, so you might want to consider avoiding multi-dimensional arrays in this scenario.
Something like this:
$merged_array = array_merge($array1, $array2);
$serialized_array = array_map("serialize", $merged_array);
$filtered_array = array_unique($serialized_array);
$final_array = array_map("unserialize", $filtered_array);
There isn't a direct function for handling what you are looking for in php, probably you need to write a function for it.
What I understood from your question is that you have 2 arrays :
$a = array( array( 'name' => 'Omid' ), 12 );
$b = array( array( 'name' => 'testing' ) );
and you want to merge them to get
$merge = array( array( 'name' => 'testing' ), 12 );
if that's what you want then you might want to take a look at this comment array merge recursive which leads to this code :
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
$merged = $array1;
foreach ( $array2 as $key => &$value )
{
if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
{
$merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
}
else
{
$merged [$key] = $value;
}
}
return $merged;
}
Does php's array_diff() do what you want?
http://us.php.net/manual/en/function.array-diff.php
or more likely array_diff_assoc:
http://us.php.net/manual/en/function.array-diff-assoc.php
Does array_diff work for you?
Description
array array_diff ( array $array1 , array $array2 [, array $ ... ] )
Compares array1 against array2 and returns the difference.

Categories