Check multiple values in array using array_intersect - php

I have this two arrays & two methods. $inputArray can be either only[1,2] or it can be[1,2,3,4].
$inputArray = [1,2];
$inputArray = [1,2,3,4];
$mainArray=[1,2,3,4,6,7,9];
$testObj->method1();
$testObj->method2();
Now need to execute method 1 only when there is no [1,2] in array.
I tried something like this but it fails for $inputArray.
if( count( $mainArray ) == count( array_intersect( $mainArray, $inputArray ) ) ) {
$testObj->method1();
} else {
$testObj->method2();
}
This is pseudocode.

Try in_array() function:
if(!in_array("1", $inputArray) && !in_array("2", $inputArray)) {
$testObj->method1();
}

How ever you question is confusing like
1. when you say you want to execute the method1 executed only when there is no [1,2] in array. so are you just point to specific 1 and 2 or count of 2 because 1 and 2 is also in the second array [1,2,3,4]
so in my mind as you are saying 3,4 is not in your desired array so i think below code will help you
<?php
$inputArray = [1,2];
//$inputArray = [1,2,3,4]; // uncomment the line and check your condition
$mainArray=[1,2,3,4,6,7,9];
// as in your desired array 3 and 4 is not so just check for that you can
// also use the condition like `in_array('3', $inputArray) || in_array('4', $inputArray)
if( in_array('3', $inputArray) ) {
echo "<br />Method 2";
} else {
echo "<br />Method 1";
}
?>
I hope this will solve the problem.

Your condition is always false. array_intersect() returns an array that contains the elements that are common to all its arguments. The result cannot be the largest array provided as argument. It is the smallest one or a subset of it.
The condition:
count(array_intersect($mainArray, $inputArray)) == count($inputArray)
is true when all the elements of $inputArray are present in $mainArray.
count(array_intersect($mainArray, $inputArray)) > 0
is true when at least one element of $inputArray is present in $mainArray. Of course,
count(array_intersect($mainArray, $inputArray)) == 0
when no element of $inputArray is present in $mainArray.
Use the one that matches your needs.

Related

PHP: counting all the items of a multilevel array containing a given parameter and a given value

I'm trying to build a function to count all the items of an array containing a given parameter, but, if the parameter is not given when calling the function, the function should count all the items. Parameters are passed with an array $params: This is what I have done so far:
function myfunction($params){
global $myArray;
if ( !isset($params[0]) ){ $params[0] = ???????? } // I need a wildcard here, so that, if the parameter is not given, the condition will be true by default
if ( !isset($params[1]) ){ $params[1] = ???????? } // I need a wildcard here, so that, if the parameter is not given, the condition will be true by default
....etc......
foreach($myArray as $item){
if ($item[0] == $params[0]){ // this condition should be true if parameter is not given
if ($item[1] == $params[1]){// this condition should be true if parameter is not given
$count += $item
}
}
}
return $count;
}
I would like:
myfunction(); //counts everything
myfunction( array ('0' => 'banana') ); //counts only $myArray['0'] = banana
myfunction( array ('0' => 'apple', '1' => 'eggs') ); //counts only $myArray['0'] = apples and $myArray['1'] = eggs
I have several $params[keys] to check this way.
I guess, if I should assign a default value to params[key] (like a wildcard) , so that, if it is not given, the function will take all the $item. I mean something that $item[0] will always be (==) equal to. Thanks. [See my answer for solution]
The way your function is declared, you have to pass a parameter. What you want to do is have a default value so that your code inside the function can detect that:
function myfunction($params=NULL)
{
global $myArray;
if (empty($params))
{
// count everything
}
else
{
// count what's listed in the $params array
}
}
EDIT
If I read your comments correctly, $myArray looks something like this:
$myArray=array
(
'apple'=>3, // 3 apples
'orange'=>4, // 4 oranges
'banana'=>2, // 2 bananas
'eggs'=>12, // 12 eggs
'coconut'=>1, // 1 coconut
);
Assuming that's true, what you want is
function myfunction($params=NULL)
{
global $myArray;
$count=0;
if (empty($params)) // count everything
{
foreach ($myArray as $num) // keys are ignored
$count += $num;
}
else if (!is_array($params)) // sanity check
{
// display an error, write to error_log(), etc. as appropriate
}
else // count what's listed in the $params array
{
foreach ($params as $key) // check each item listed in $params
if (isset($myArray[$key])) // insure request in $myArray
$count += $myArray[$key]; // add item's count to total
}
return $count;
}
This will give you
myfunction(); // returns 22
myfunction(array('banana')); // returns 2
myfunction(array('apple','eggs')); // returns 15
myfunction(array('tomatoes')); // returns 0 - not in $myArray
If this isn't the result you're looking for, you need to rewrite your question.
EDIT # 2
Note that because arrays specified without explicit keys are keyed numerically in the order the elements are listed, the function calls I showed above are exactly equivalent to these:
myfunction(); // returns 22
myfunction(array(0=>'banana')); // returns 2
myfunction(array(0=>'apple',1=>'eggs')); // returns 15
myfunction(array(0=>'tomatoes')); // returns 0 - not in $myArray
However, the calls are not equivalent to these:
myfunction(); // returns 22
myfunction(array('0'=>'banana')); // returns 2
myfunction(array('0'=>'apple','1'=>'eggs')); // returns 15
myfunction(array('0'=>'tomatoes')); // returns 0
In this case, explicit string keys are specified for the array, and while the strings' values will evaluate the same as the numerical indices under most circumstances, string indices are not the same as numerical ones.
The code you proposed in your answer has a few errors:
foreach($myArray as $item)
{
foreach ($params as $key => $value)
{
if ( isset($params[$key]) && $params[$key] == $item[$key] )
{
$count += $item
}
}
}
First, isset($params[$key]) will always evaluate to TRUE by the nature or arrays and foreach. Second, because of your outer foreach loop, if your $myArray is structured as I illustrated above, calling myfunction(array('apple')) will result in $params[$key] == $item[$key] making these tests because $key is 0:
'apple' == 'apple'[0] // testing 'apple' == 'a'
'apple' == 'orange'[0] // testing 'apple' == 'o'
'apple' == 'banana'[0] // testing 'apple' == 'b'
'apple' == 'eggs'[0] // testing 'apple' == 'e'
'apple' == 'coconut'[0] // testing 'apple' == 'c'
As you can see, this will not produce the expected results.
The third problem with your code is you don't have a semicolon at the end of the $count += $item line, so I'm guessing you didn't try running this code before proposing it as an answer.
EDIT # 3
Since your original question isn't terribly clear, it occurred to me that maybe what you're trying to do is count the number of types of things in $myArray rather than to get a total of the number of items in each requested category. In that case, the last branch of myfunction() is even simpler:
else // count what's listed in the $params array
{
foreach ($params as $key) // check each item listed in $params
if (isset($myArray[$key])) // insure request in $myArray
$count++; // add the item to the total
}
With the sample $myArray I illustrated, the above change will give you
myfunction(); // returns 5
myfunction(array('banana')); // returns 1
myfunction(array('apple','eggs')); // returns 2
myfunction(array('tomatoes')); // returns 0 - not in $myArray
Again, if neither of these results are what you're looking for, you need to rewrite your question and include a sample of $myArray.
MY SOLUTION
(Not extensively tested, but works so far)
Following #FKEinternet answer, this is the solution that works for me: obviously the $params should use the same keys of $item. So, foreach iteration if parameter['mykey'] is given when calling the function and its value is equal to item['mykey'], count the iteration and $count grows of +1
function myfunction($params=NULL){
global $myArray;
foreach($myArray as $item){
foreach ($params as $key => $value){
if ( isset($params[$key]) && $params[$key] == $item[$key] ){
$count += $item;
}
}
}
return $count;
}
Thanks everybody for all inputs!!

PHP : How can I check Array in array?

I have 1 array, and the this array contains is an array also for each element. ex:
$arraycenter = array(
array('a','b','c','d'), //array1
array('e','d','f','g'), //array2
array('a','b','c','d'), //array3
array('e','d','f','g'), //array4
array(.............. ), //.....
array(...............); //array++
How can check array1 & array3 is the same, and array2 & array 4 is the same?
You can use the === operator:
if ($arraycenter[0] === $arraycenter[2] && $arraycenter[1] === $arraycenter[3]) {
// do stuff...
}
You can use array_diff
if (array_diff($arraycenter[1], $arraycenter[2], $arraycenter[3]))
// Do something
Or (if you don't know how many items need to be checked) you can use array_filter
$array_center = array_filter($array_center, function($value) use(&$array_center)
{
return array_diff($array_center[1], $value);
}

PHP value in an array

Hi I'm working on a checking a given array for a certain value.
my array looks like
while($row = mysqli_fetch_array($result)){
$positions[] = array( 'pos' => $row['pos'], 'mark' => $row['mark'] );
}
I'm trying to get the info from it with a method like
<?php
if(in_array('1', $positions)){
echo "x";
}
?>
This I know the value '1' is in the array but the x isn't being sent as out put. any suggestions on how to get "1" to be recognized as being in the array?
Edit:
I realize that this is an array inside of an array. is it possible to combine in_array() to say something like:
"is the value '1' inside one of these arrays"
in_array is not recursive. You're checking if 1 is in an array of arrays which doesn't make sense. You'll have to loop over each element and check that way.
$in = false;
foreach ($positions as $pos) {
if (in_array(1, $pos)) {
$in = true;
break;
}
}
in_array only checks the first level. In this case, it only sees a bunch of arrays, no numbers of any kind. Instead, consider looping through the array with foreach, and check if that 1 is where you expect it to be.
That's because $positions is an array of arrays (a multi-dimensional array).
It contains no simple '1'.
Try a foreach-loop instead:
foreach($postions as $value)
if ($value["pos"] == '1')
echo "x ".$value["mark"];
The problem is that 1 isn't actually in the array. It's in one of the array's within the array. You are comparing the value 1 to the value Array which obviously isn't the same.
Something like this should get you started:
foreach ($positions as $position) {
if ($position['pos'] == 1) {
echo "x";
break;
}
}
Your array $positions is recursive, due to the fact that you use $positions[] in your first snippet. in_array is not recursive (see the PHP manual). Therefore, you need a custom function which works with recursive arrays (source):
<?php
function in_arrayr( $needle, $haystack ) {
foreach( $haystack as $v ){
if( $needle == $v )
return true;
elseif( is_array( $v ) )
if( in_arrayr( $needle, $v ) )
return true;
}
return false;
}
?>
Instead of calling in_array() in your script, you should now call in_arrayr().

How to remove all instances of duplicated values from an array

I know there is array_unique function, but I want to remove duplicates. Is there a built-in function or do I have to roll my own.
Example input:
banna, banna, mango, mango, apple
Expected output:
apple
You can use a combination of array_unique, array_diff_assoc and array_diff:
array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
You can use
$singleOccurences = array_keys(
array_filter(
array_count_values(
array('banana', 'mango', 'banana', 'mango', 'apple' )
),
function($val) {
return $val === 1;
}
)
)
See
array_count_values — Counts all the values of an array
array_filter — Filters elements of an array using a callback function
array_keys — Return all the keys or a subset of the keys of an array
callbacks
Just write your own simple foreach loop:
$used = array();
$array = array("banna","banna","mango","mango","apple");
foreach($array as $arrayKey => $arrayValue){
if(isset($used[$arrayValue])){
unset($array[$used[$arrayValue]]);
unset($array[$arrayKey]);
}
$used[$arrayValue] = $arrayKey;
}
var_dump($array); // array(1) { [4]=> string(5) "apple" }
have fun :)
If you want to only leave values in the array that are already unique, rather than select one unique instance of each value, you will indeed have to roll your own. Built in functionality is just there to sanitise value sets, rather than filter.
You want to remove any entries that have duplicates, so that you're left with only the entries that were unique in the list?
Hmm it does sound like something you'll need to roll your own.
There is no existing function; You'll have to do this in two passes, one to count the unique values and one to extract the unique values:
$count = array();
foreach ($values as $value) {
if (array_key_exists($value, $count))
++$count[$value];
else
$count[$value] = 1;
}
$unique = array();
foreach ($count as $value => $count) {
if ($count == 1)
$unique[] = $value;
}
The answer on top looks great, but on a side note: if you ever want to eliminate duplicates but leave the first one, using array_flip twice would be a pretty simple way to do so. array_flip(array_flip(x))
Only partially relevant to this specific question - but I created this function from Gumbo's answer for multi dimensional arrays:
function get_default($array)
{
$default = array_column($array, 'default', 'id');
$array = array_diff($default, array_diff_assoc($default, array_unique($default)));
return key($array);
}
In this example, I had cached statuses and each one other than the default was 0 (the default was 1). I index the default array from the IDs, and then turn it into a string. So to be clear - the returned result of this is the ID of the default status providing it's in the same part of the multi dimensional array and not the key of it
PHP.net http://php.net/manual/en/function.array-unique.php
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.
New solution:
function remove_dupes(array $array){
$ret_array = array();
foreach($array as $key => $val){
if(count(array_keys($val) > 1){
continue;
} else {
$ret_array[$key] = $val;
}
}

PHP: How do I check the contents of an array for my string?

I a string that is coming from my database table say $needle.
If te needle is not in my array, then I want to add it to my array.
If it IS in my array then so long as it is in only twice, then I still
want to add it to my array (so three times will be the maximum)
In order to check to see is if $needle is in my $haystack array, do I
need to loop through the array with strpos() or is there a quicker method ?
There are many needles in the table so I start by looping through
the select result.
This is the schematic of what I am trying to do...
$haystack = array();
while( $row = mysql_fetch_assoc($result)) {
$needle = $row['data'];
$num = no. of times $needle is in $haystack // $haystack is an array
if ($num < 3 ) {
$$haystack[] = $needle; // hopfully this adds the needle
}
} // end while. Get next needle.
Does anyone know how do I do this bit:
$num = no. of times $needle is in $haystack
thanks
You can use array_count_values() to first generate a map containing the frequency for each value, and then only increment the value if the value count in the map was < 3, for instance:
$original_values_count = array_count_values($values);
foreach ($values as $value)
if ($original_values_count[$value] < 3)
$values[] = $value;
As looping cannot be completely avoided, I'd say it's a good idea to opt for using a native PHP function in terms of speed, compared to looping all values manually.
Did you mean array_count_values() to return the occurrences of all the unique values?
<?php
$a=array("Cat","Dog","Horse","Dog");
print_r(array_count_values($a));
?>
The output of the code above will be:
Array (
[Cat] => 1,
[Dog] => 2,
[Horse] => 1
)
There is also array_map() function, which applies given function to every element of array.
Maybe something like the following? Just changing Miek's code a little.
$haystack_count = array_count_values($haystack);
if ($haystack_count[$needle] < 3)
$haystack[] = $needle;

Categories