PHP check if array contains multiple values - php

I have an array like this fetched from a database:
[0] => Array (
[permission_id] => 1
)
[1] => Array (
[permission_id] => 2
)
I would like to check if this array contains multiple values with a function. For example:
function checkIfArrayContains($array)
{
...
}
$array = array(1, 2);
checkIfArrayContains($array); //Should return true
$array = array(2);
checkIfArrayContains($array); //Should return true
$array = array(1, 2, 3);
checkIfArrayContains($array); //Should return false
How could this be achieved using PHP?

If you are only getting one column from the database, and you use PDO, I would suggest you use the fetch mode FETCH::COLUMN, to gain an array that looks like
$arr = [1, 2];
Then you can simply use in_array to check for the value

Here's a suggestion:
$dbPermissions = [
['permission_id' => 1],
['permission_id' => 2],
];
function hasSufficientPermissions(array $dbPermissions, array $permissions): bool
{
$dbPermissionValues = array_column($dbPermissions, 'permission_id');
return empty(array_diff($permissions, $dbPermissionValues));
}
var_dump(hasSufficientPermissions($dbPermissions, [1, 2]));
var_dump(hasSufficientPermissions($dbPermissions, [2]));
var_dump(hasSufficientPermissions($dbPermissions, [1, 2, 3]));
This will output:
true
true
false
How it works:
array_column reduces your database array to [1, 2]
array_diff finds values in the first array supplied that are not present in the second array supplied
if a difference exists, then false should be returned - this is where we utilize empty

Related

Is there a way to access a json object elements using PHP

I am trying to get a data from my own API using PHP \
My PHP code :
$cart = json_decode(file_get_contents("php://input",true));
foreach ($cart->thoubss as $a){
echo($a['0']); // trying to get the first element in the array (4) in the first iteration and then (3) in the second iteration
echo($a['1']); // trying to get the first element in the array (5) in the first iteration and then (3) in the second iteration
}
My JSON input :
{"thoubss":"{'0': [4, 5], '1': [5, 3]}"}
I am getting
PHP Warning: Invalid argument supplied for foreach()
print_r($cart) output
stdClass Object
(
[thoubss
] => {'0': [
4,
5
], '1': [
5,
3
]
}
)
Try with
$cart = json_decode(file_get_contents("php://input",true),true);
json_decode will return an array instead of an stdClass object
You can use this method also.
$cart = json_decode(file_get_contents("php://input",true),true);
This will return an array like below.
$cart = array(
"thoubss" => array(
'0' => array(4, 5),
'1' => array(5, 3)
)
);
Now you can use like below:
foreach ($cart['thoubss'] as $a){
echo $a[0];
echo $a[1];
}

Get array containing smallest values using min()

The documentation for min() shows the following example:
// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)
Given the following code:
$input = [
[3, 6],
[2, 9],
];
var_dump(min(...$input)); // returns [2, 9] as expected
If you make the same array associative, it fails and always seems to just return the first array:
$input = [
["three" => 3, "six" => 6],
["two" => 2, "nine" => 9],
];
var_dump(min(...$input)); // returns ["three" => 3, "six" => 6]
Why?
Here's an example
According to the documentation values are compared using the standard comparison rules.
In the table of "comparison with various types" there, it states that if both operands are arrays and a key in operand 1 is not present in operand 2, then the arrays are not comparable. This is why min simply returns whatever is the first value in your array.
Specifically, arrays are compared as follows:
If one array has fewer values than the other, it is smaller.
Otherwise if any key in operand 1 is not in operand 2, the arrays are uncomparable.
For each value in operand 1 in turn, compare with the value with the same key in operand 2.
If the same, continue comparing values.
Otherwise the smaller array is the one with the smaller value.
Because they are not comparable, min is simply returning the first array in the list. If you swap the order, the other array will be returned. You can see this if you sort the array with sort($input). Every time you sort it the array is reversed.
To get the behaviour you desire, sort the arrays based on their values and then fetch the first element. But be aware that this will depend which key you defined first, so ["three" => 3, "six" => 6] is not the same as ["six" => 6, "three" => 3].
usort($input, function($a, $b) { return array_values($a) <=> array_values($b); });
var_dump($input[0]);
Just convert them to simple arrays and then return the associative array associated to the result of min.
<?php
function array_min_assoc(){
$args = func_get_args();
$not_assoc = array_map('array_values',$args);
$min = min(...$not_assoc);
$key = array_search($min, $not_assoc);
if ($key !== false){
return $args[$key];
}
}
$input = [
["three" => 3, "six" => 6],
["two" => 2, "nine" => 9],
];
var_dump(array_min_assoc(...$input));
/* returns
array(2) {
["two"] => int(2)
["nine"]=> int(9)
}
*/

PHP Array Search Return Multiple Keys

I'm trying to search an array and return multiple keys
<?php
$a=array("a"=>"1","b"=>"2","c"=>"2");
echo array_search("2",$a);
?>
With the code above it only returns b, how can I get I to return b and c?
As it says in the manual for array_search:
To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
Example:
$a=array("a"=>"1","b"=>"2","c"=>"2");
print_r(array_keys($a, "2"));
Result:
Array
(
[0] => b
[1] => c
)
I am adding this in case someone finds it helpful. If you're doing with multi-dimensional arrays.
Suppose you have this
$a = array(['user_id' => 2, 'email_id' => 1], ['user_id' => 2, 'email_id' => 2, ['user_id' => 3, 'email_id' => 1]]);
You want to find email_id of user_id 2.
You can do this
print_r(array_keys(array_column($a, 'user_id'), 2));
This will return [0,1]
Hope this helps.
use array_keys instead:
<?php
$a=array("a"=>"1","b"=>"2","c"=>"2");
echo array_keys(array($a, "2");
?>

Re-order the array order both key and value

Say I've got an array
[0]=>test
[2]=>example.
I want o/p as
[0]=>test
[1]=>example
In my first array
[1]=>NULL
I've tried to remove this and reorder so, I used array_filter() to remove the null value.
Now, how do I reorder the array?
If I understand what you need, I think array_values should help (it will return only the values in the array, reindexed from 0):
print_r( array_values($arr) );
Here's an example of this: http://codepad.org/q7dVqyVY
You might want to use merge:
$newArray = array_merge(array(),$oldArray);
$Array = array('0'=>'test,', '2'=>'example');
ksort($Array);
$ArrayTMP = array_values($Array);
or
$Array = array('0'=>'test,', '2'=>'example');
ksort($Array);
$ArrayTMP = array_merge ($Array,array());
Credit goes to: http://www.codingforums.com/archive/index.php/t-17794.html.
<?php
$a = array(0 => 1, 1 => null, 2 => 3, 3 => 0);
$r = array_values(
array_filter($a, function ($elem)
{
if ( ! is_null($elem))
return true;
})
);
// output:
array (
0 => 1,
1 => 3,
2 => 0,
)
?>
NOTE: I am using an anonymous callback function for array_filter. Anonymous callback only works in php 5.3+ and is the appropriate in this case (IMHO). For previous versions of php just define it as normal.

PHP Built-in Method to Get Array Values Given a List of Keys

I have an 'dictionary' array such as this:
$arr['a']=5;
$arr['b']=9;
$arr['as']=56;
$arr['gbsdfg']=89;
And I need a method that, given a list of the array keys, I can retrieve the corresponding array values. In other words, I am looking for a built-in function for the following methods:
function GetArrayValues($arrDictionary, $arrKeys)
{
$arrValues=array();
foreach($arrKeys as $key=>$value)
{
$arrValues[]=$arrDictionary[$key]
}
return $arrValues;
}
I am so sick of writing this kind of tedious transformation that I have to find a built-in method to do this. Any ideas?
array_intersect_key
If you have an array of keys as values you can use array_intersect_key combined with array_flip. For example:
$values = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$keys = ['a', 'c'];
array_intersect_key($values, array_flip($keys));
// ['a' => 1, 'c' => 3]

Categories