How to get unique value from array in PHP? - php

I have two array inputs like this :
$array1 = [1,2,3,4,6];
$array2 = [1,3];
$output = array_merge(array_diff($array1,$array2),array_diff($array2,$array1));
Now I want to check array1 with array 2 and eliminate 1 and 3 in $array1
and the output I am expecting is
$output = [2,4,6];
but in this method I get some bugs, when array2 have single value e.g.: $array2 = [1]; , $array1 = [1,2,3,4,6]; the output should be $output = [2,3,4,6];. But I am getting $array1 all values [1,2,3,4,6];

Simple :)
(Just un-complicate your code and you don't need anything new for that)
<?php
$array1 = array(1,2,3,4,6);
$array2 = array(1,3);
$result = array_diff($array1, $array2);
print_r($result);
?>
Demo
In Your style it can even be a one liner :P
<?php print_r(array_diff(array(1,2,3,4,6), array(1,3))); ?>

Related

How to check it elemets of an array are in another array

I have an issue,
I have this array
$items= array('ABC','DEF',GHI');
and have another two arrays
$array1 = array('ABC','DEF',GHI');
$array2 = array('DEF');
$array1 should return TRUE because all elements are in $items
$array2 should return FALSE because 'ABC' and 'GHI' arent in that array
i've tried with array_intersect and array_diff but i cant get it,
$result = array_intersect($items,$array1);
$result = !array_diff($items,$array1);
Could you please help me?
Regards
Mario
To see if the array contains at least all values in $items, just get all values from the array that are also in $items and compare it with $items:
$result = (array_intersect($array1, $items) == $items);
If you just need to compare the arrays:
$result = ($array1 == $items);
But why is this not working for you:
$result = !array_diff($items, $array1);
If you dont want to use array_diff, you can use the multidimensional arrays.
Put your arrays inside another array:
$items1= array(
array(0=>"ABC", 1=> "DEF", 2=>"GHI"),
array(0=>"ABC", 1=> "DEF", 2=>"GHI"),
array(0=>"DEF"),
);
Check them with conditional statements:
if($items1[0]==$items1[1]){
echo "true";
}if($items1[1]==$items1[2]){
echo "true 2";
}else{
echo "false";
}

Trying to remove duplicates from JSON array with array_unique and array_values

I was following this but it still doesn't work for me: How to remove duplicate data of JSON object using PHP
In my PHP file I have 3 JSON arrays:
{"results":[{"cat_id":2,"cat_name":"veterinarian"},{"cat_id":3,"cat_name":"electrician"},
{"cat_id":4,"cat_name":"dentist"}]}
Array2:
{"results":[{"cat_id":"8","cat_name":"dental hygienist"},{"cat_id":"5","cat_name":"stocktaker"},
{"cat_id":"9","cat_name":"builder"}]}
Array3:
{"results":[{"cat_id":4,"cat_name":"dentist"},{"cat_id":5,"cat_name":"stocktaker"},
{"cat_id":3,"cat_name":"electrician"}]}
I want to merge these and remove duplicates. I'm trying like this:
//this works good, all merged into one
$array1AndArray2AndArray3 = array_merge_recursive($array1,$array2, $array3);
//now I want to remove duplicates:
$uniqueArray = array_values(array_unique($array1AndArray2AndArray3, SORT_REGULAR));
echo "Unique array is " . json_encode($uniqueArray);
But I am getting:
Unique array is [[{"cat_id":2,"cat_name":"veterinarian"},{"cat_id":3,"cat_name":"electrician"},
{"cat_id":4,"cat_name":"dentist"},
{"cat_id":"8","cat_name":"dental hygienist"},{"cat_id":"5","cat_name":"stocktaker"},
{"cat_id":"9","cat_name":"builder"},
{"cat_id":4,"cat_name":"dentist"},
{"cat_id":5,"cat_name":"stocktaker"},
{"cat_id":3,"cat_name":"electrician"}]]
As you can see, duplicates are not removed, and there's extra [] and "results" is missing.
Can you tell me how I can fix this, or another way to do it?
Use below solution
$array1 = '{"results":[{"cat_id":2,"cat_name":"veterinarian"},{"cat_id":3,"cat_name":"electrician"},{"cat_id":4,"cat_name":"dentist"}]}';
$array2 = '{"results":[{"cat_id":"8","cat_name":"dental hygienist"},{"cat_id":"5","cat_name":"stocktaker"},{"cat_id":"9","cat_name":"builder"}]}';
$array3 = '{"results":[{"cat_id":4,"cat_name":"dentist"},{"cat_id":5,"cat_name":"stocktaker"},{"cat_id":3,"cat_name":"electrician"}]}';
$array1 = json_decode($array1, TRUE);
$array2 = json_decode($array2, TRUE);
$array3 = json_decode($array3, TRUE);
$array4 = array_merge_recursive($array1['results'], $array2['results'], $array3['results']);
$uniqueArray['results'] = array_values(array_unique($array4, SORT_REGULAR));

Say how many items are the same in 2 arrays?

Is there a way within PHP and MySQL to be able to compare 2 different array (list) variables and say how many items are the same
For example,
$array1 = "hello, bye, google, laptop, yes";
$array2 = "google, bye, windows, no, phone";
Then an echo statement would say how many items are the same. In this example, it would be 2 and this would be echoed.
This is different to most array questions because of the way my site is set up using commas which can make it quite complicated
Try array_intersect() function in php
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r(count($result));
?>
You can count elements in the output array using count() function,
doc link
$array_new1 = explode(',',$array1);
$array_new2 = explode(',',$array2);
$array_1 = array_map('trim', $array_new1);
$array_2 = array_map('trim', $array_new2);
$data =array();
foreach($array_2 as $value){
if(in_array($value,$array_1)){
$data[] = $value;
}
}
echo count($data);
First you have to convert your string to array with trim. Then use
array_intersect to get common values.
$array1 = "hello, bye, google, laptop, yes";
$array2 = "google, bye, windows, no, phone";
$array_new1 = array_map('trim', explode(',', $array1));
$array_new2 =array_map('trim', explode(',', $array2));
$common = array_intersect($array_new1, $array_new2);
print_r($common);
echo count($common);

php to create an array with value stored in variables

well, i have 2 variables
$variable1 = "123";
$variable2 = "321";
both variables are calculated by other methods and may vary due to change of circumstances, now i want to put these values in a single array for displaying, what i want is something like this
$array = ($variable1, $variable2)
and print like(in IDE)
array([0]=>123 [1]=>321)
both 123 and 321 are representations of variable values.
i tried compact() function but it gave me something weird, i tried make these two variables an array with only one element and merge them into one array but in fact i have many variables and it's infeasible to do this for every one of them.....please show me how i can do it and explain in detail the mechanism behind it, thank you very much.
There are several ways to do what you want.
You can use one of examples below :
// Define a new array with the values
$array1 = array($variable1, $variable2);
// Or
$array2 = [$variable1, $variable2];
// Debug
print_r($array1);
print_r($array2);
// Define an array and add the values next
$array3 = array();
$array3[] = $variable1;
$array3[] = $variable2;
// Debug
print_r($array3);
// Define an array and push the values next
// http://php.net/manual/en/function.array-push.php
$array4 = array();
array_push($array4, $variable1);
array_push($array4, $variable2);
// Debug
print_r($array4);
Just use the array function to get the values into one array.
$var1 = "123";
$var2 = "321";
$array = array($var1,$var2);
var_dump($array); returns:
array (size=2)
0 => string '123' (length=3)
1 => string '321' (length=3)
Or another example on how you could do it is:
$array = array();
$array[] = myFunction(); //myFunction returns a value and by using $array[] you can add the value to the array.
$array[] = myFunction2();
var_dump($array);
Here is your answer
$variable1 = "123";
$variable2 = "321";
$arr =array();
array_push($arr,$variable1);
array_push($arr,$variable2);
echo '<pre>';
print_r($arr);
Hope this will solve your problem.
As you want to put these item in array
First you have to initialize a variable
$newArray = []
After that you have to store the value in array which can be done by this
$newArray[] = $variable1;
// OR BY
array_push($newArray, $variable1);
They both are same it push the data to the end of the array
So your code will be like this
$newArray = []
$newArray[] = $variable1;
$newArray[] = $variable2;
If you want to do it in loop then do somthing like this
$newArray = []
foreach($values as $value){
$newArray[] = $value;
}
If there is a fix value then you can do like this
$newArray = [$variable1, $variable2];
//OR BY
$newArray = array($variable1, $variable2);
Both are same
And to print the value use
print_r($newArray);
Hope this will help

Subtracting arrays to get every difference

What I have
$array1 = [1,1,1];
$array2 = [1,1];
What I'm doing:
array_diff( $array1, $array2 );
What I expected:
array(1) { 1 }
What I got
array(0) { }
How do I subtract two arrays to get every discrepancy?
Edit:
My example was incomplete, sorry.
If we also have values like this:
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
I would expect
[1,1,2,1] - [1,1,1,2] = []
array_diff_assoc() is the right way to go here. But to get your expected result you just have to sort the array first with usort() where I compare the values with strcasecmp().
So this should work for you:
<?php
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
function caseCmpSort($a, $b){
return strcasecmp($a, $b);
}
usort($array1, "caseCmpSort");
usort($array2, "caseCmpSort");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
output:
Array ( )
use array_diff_assoc
$array1 = [1,1,1];
$array2 = [1,1];
print_r(array_diff_assoc( $array1, $array2)); // outputs Array ([2] => 1)
try it here http://sandbox.onlinephpfunctions.com/code/43394cc048f8c9660219e4fa30386b53ce4adedb
So you should check array key differences too. Have you tried array_diff_assoc()?
http://php.net/manual/en/function.array-diff-assoc.php
From manual:
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
So, it is working as expected. I am not sure what exactly You want to achieve. You cloud try, it should give You expected result in this example.
$a = [1,1,1];
$b = [1,1];
print_r(array_diff_assoc($a,$b));
Edit: Well, simple sort should solve issue from Your comment. Nothe, that this will remove information of original indexes of elements.
$a = [1,1,2,1];
$b = [1,1,1,2,1];
sort($a);
sort($b);
print_r(array_diff_assoc($a,$b));
<?php
$n = array(1,1,1);
$m = array(1,1);
$r = array_diff_assoc($n,$m);
var_dump($r);
?>

Categories