filter array values from a dictionary - php

I have an $array on php, and I'd like to know if the values are from a specific dictionary.
For example, if my dictionary is an array of values ['cat', 'dog', 'car', 'man'] I'd like to filter my $array and return false if a word into this one is not on the dictionary.
So, if $array is :
['men', 'cat'] // return false;
['man', 'cat'] // return true;
['cat', 'dogs'] // return false;
[''] // return false;
and so on...
How can I filter an array in this manner?

function checkDictionary($array,$dictionary){
foreach($array as $array_item){
if(!in_array($array_item,$dictionary)){
return false;
}
}
return true;
}
you can also do something like:
function checkDictionary($array,$dictionary){
$result = (empty(array_diff($array,$dictionary))) ? true : false;
return $result;
}

To increase performance, you should convert you "dictionary" to an associative array, where the keys are the words in the dictionary:
$dict = array_flip($dict);
Then all you have to do is to loop over the values you search for, which is O(n):
function contains($search, $dict) {
foreach($search as $word) {
if(!array_key_exists($word, $dict)) {
return false;
}
return true;
}
Reference: array_flip, array_key_exists

function doValuesExist($dictionary, $array) {
return (count(array_intersect($dictionary,$array)) == count($array));
}

Related

How to check in PHP that any values exist in array in addition to some fixed value

I have an array like this:
$array = array('static_value_1', 'static_value_2', 'extra_value_1', 'extra_value_2');
How could I return true if any value exists in array in addition to static_value_1 and/or static_value_2?
For example this array should return true:
array = array('static_value_1', 'static_value_2', 'extra_value_1');
and this one false:
array = array('static_value_1', 'static_value_2');
Thanks!
I think just looping looking for non-static should work:
function check_array($check) {
$static=Array('static_value_1', 'static_value_2');
// Dealing with empty array.
if(count($check)==0) return false;
foreach($check as $value) {
// If value is not in static collection is an addition...
if(!in_array($value, $static)) {
return false;
}
}
return true;
}

find if key is in a multidimentional array

i am creating a multidimentional array and i wish to know why the following code is not working and why the other with same value when im fetching the same array is actually working.
$fruits = array(
"sale"=> array("banana", "apple", "orange"),
"regular"=> array("grapes", "pear", "ananas")
);
then in the first case it return false
1st case :
$find_price = 'sale';
if(in_array($find_price, $fruits)){
return true;
}
else {
return false;
}
and in second example i got a result of true
$find_price = 'sale';
if(isset($fruit[$find_price])){
return true;
}
else {
return false;
}
in_array() used to determine the value is in array or not. If you want to find if the key exist so array_key_exists is your friend
Look at the below snippet.
$find_price = 'sale';
if(array_key_exists($find_price, $fruits)){
return true;
}
else {
return false;
}
In your first code
$find_price = 'sale';
if(in_array($find_price, $fruits)){
return true;
}
else {
return false;
}
You use in_array(). This in_array() function the elements into the array, That element exist in array or not. And you are finding a value which is key in the array. Instead of in_array() you can use array_key_exists().
Your second code
$find_price = 'sale';
if(isset($fruit[$find_price])){
return true;
}
else {
return false;
}
You are using isset() this function tell that the element you find, is exist in code or not. Like you are finding isset($fruit[$find_price]) means isset($fruit['sale']) that is exist....
Thats why this condition is true..
You have to use loop for this type of conditions. try this.
foreach($fruits as $key => $value)
{
if($fruits[$key]['sale'])
{
return true;
}
else
{
return false;
}
}

Check if string is equal to one of many given strings

I want to check whether string is one of the given strings. It would look something like this.
$string 'test';
// if given string is 'test' function will return false.
function checkIfIsSubstring($string)
{
if (strcmp($string, 'test2') )
return true;
if (strcmp($string, 'test3') )
return true;
if (strcmp($string, 'test4') )
return true;
return false;
}
is there php function what would do same thing, without me creating a new function?
You can put the values into an array and then use in_array():
$array = array('test1', 'test2', 'test3');
$string = 'test1';
if(in_array($string, $array)) {
// do something
}

More concise way to check to see if an array contains only numbers (integers)

How do you verify an array contains only values that are integers?
I'd like to be able to check an array and end up with a boolean value of true if the array contains only integers and false if there are any other characters in the array. I know I can loop through the array and check each element individually and return true or false depending on the presence of non-numeric data:
For example:
$only_integers = array(1,2,3,4,5,6,7,8,9,10);
$letters_and_numbers = array('a',1,'b',2,'c',3);
function arrayHasOnlyInts($array)
{
foreach ($array as $value)
{
if (!is_int($value)) // there are several ways to do this
{
return false;
}
}
return true;
}
$has_only_ints = arrayHasOnlyInts($only_integers ); // true
$has_only_ints = arrayHasOnlyInts($letters_and_numbers ); // false
But is there a more concise way to do this using native PHP functionality that I haven't thought of?
Note: For my current task I will only need to verify one dimensional arrays. But if there is a solution that works recursively I'd be appreciative to see that to.
$only_integers === array_filter($only_integers, 'is_int'); // true
$letters_and_numbers === array_filter($letters_and_numbers, 'is_int'); // false
It helps to define two helper, higher-order functions:
/**
* Tell whether all members of $elems validate the $predicate.
*
* all(array(), 'is_int') -> true
* all(array(1, 2, 3), 'is_int'); -> true
* all(array(1, 2, 'a'), 'is_int'); -> false
*/
function all($elems, $predicate) {
foreach ($elems as $elem) {
if (!call_user_func($predicate, $elem)) {
return false;
}
}
return true;
}
/**
* Tell whether any member of $elems validates the $predicate.
*
* any(array(), 'is_int') -> false
* any(array('a', 'b', 'c'), 'is_int'); -> false
* any(array(1, 'a', 'b'), 'is_int'); -> true
*/
function any($elems, $predicate) {
foreach ($elems as $elem) {
if (call_user_func($predicate, $elem)) {
return true;
}
}
return false;
}
<?php
$only_integers = array(1,2,3,4,5,6,7,8,9,10);
$letters_and_numbers = array('a',1,'b',2,'c',3);
function arrayHasOnlyInts($array){
$test = implode('',$array);
return is_numeric($test);
}
echo "numbers:". $has_only_ints = arrayHasOnlyInts($only_integers )."<br />"; // true
echo "letters:". $has_only_ints = arrayHasOnlyInts($letters_and_numbers )."<br />"; // false
echo 'goodbye';
?>
Another alternative, though probably slower than other solutions posted here:
function arrayHasOnlyInts($arr) {
$nonints = preg_grep('/\D/', $arr); // returns array of elements with non-ints
return(count($nonints) == 0); // if array has 0 elements, there's no non-ints
}
There's always array_reduce():
array_reduce($array, function($a, $b) { return $a && is_int($b); }, true);
But I would favor the fastest solution (which is what you supplied) over the most concise.
function arrayHasOnlyInts($array) {
return array_reduce(
$array,
function($result,$element) {
return is_null($result) || $result && is_int($element);
}
);
}
returns true if array has only integers, false if at least one element is not an integer, and null if array is empty.
Why don't we give a go to Exceptions?
Take any built in array function that accepts a user callback (array_filter(), array_walk(), even sorting functions like usort() etc.) and throw an Exception in the callback. E.g. for multidimensional arrays:
function arrayHasOnlyInts($array)
{
if ( ! count($array)) {
return false;
}
try {
array_walk_recursive($array, function ($value) {
if ( ! is_int($value)) {
throw new InvalidArgumentException('Not int');
}
return true;
});
} catch (InvalidArgumentException $e) {
return false;
}
return true;
}
It's certainly not the most concise, but a versatile way.

php Checking if value exists in array of array

I have an array within an array.
$a = array ( 0 => array ( 'value' => 'America', ), 1 => array ( 'value' => 'England', ), )
How do I check if 'America' exists in the array? The America array could be any key, and there could be any number of subarrays, so a generalized solution please.
Looking on the php manual I see in_array, but that only works for the top layer. so something like in_array("America", $a) would not work.
Thanks.
A general solution would be:
function deep_in_array($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && deep_in_array($needle, $element))
return true;
}
return false;
}
The reason why I chose to use in_array and a loop is: Before I examine deeper levels of the array structure, I make sure, that the searched value is not in the current level. This way, I hope the code to be faster than doing some kind of depth-first search method.
Of course if your array is always 2 dimensional and you only want to search in this kind of arrays, then this is faster:
function in_2d_array($needle, $haystack) {
foreach($haystack as $element) {
if(in_array($needle, $element))
return true;
}
return false;
}
PHP doesn't have a native array_search_recursive() function, but you can define one:
function array_search_recursive($needle, $haystack) {
foreach ($haystack as $value) {
if (is_array($value) && array_search_recursive($needle, $value)) return true;
else if ($value == $needle) return true;
}
return false;
}
Untested but you get the idea.
in_array("America", array_column($a, 'value'))
function search($a,$searchval){ //$a - array; $searchval - search value;
if(is_array($a)) {
foreach($a as $val){
if(is_array($val))
if(in_array($searchval,$val)) return true;
}
}
else return false;
}
search($a, 'America'); //function call

Categories