in_array check for non false values - php

$array = array(
'vegs' => 'tomatos',
'cheese' => false,
'nuts' => 765,
'' => null,
'fruits' => 'apples'
);
var_dump(in_array(false, $array, true)); //returns true because there is a false value
How to check strictly if there is at least one NON-false (string, true, int) value in array using in_array only or anything but not foreach?
var_dump(in_array(!false, $array, true)); //this checks only for boolean true values
var_dump(!in_array(false, $array, true)); //this returns true when all values are non-false

Actual solution below
Just put the negation at the right position:
var_dump(!in_array(false, $array, true));
Of course this will also be true if the array contains no elements at all, so what you want is:
var_dump(!in_array(false, $array, true) && count($array));
Edit: forget it, that was the answer for "array contains only values that are not exactly false", not "array contains at least one value that is not exactly false"
Actual solution:
var_dump(
0 < count(array_filter($array, function($value) { return $value !== false; }))
);
array_filter returns an array with all values that are !== false, if it is not empty, your condition is true.
Or simplified as suggested in the comments:
var_dump(
(bool) array_filter($array, function($value) { return $value !== false; })
);
Of course, the cast to bool also can be omitted if used in an if clause.

How to check strictly if there is at least one NON-false (string,
true, int) value in array using in_array only or anything but not
foreach?
This is not possible because:
String: this data type can contain any value, its not like boolean (true or false) or NULL.
INT: same as string, how to check for unknown?
Boolean: possible.
NULL: possible.
Then, INT and STRING data types can't be found just using an abstract (int) or (string)!
EDIT:
function get_type($v)
{
return(gettype($v));
}
$types = array_map("get_type", $array);
print_r($types);
RESULT:
Array
(
[vegs] => string
[cheese] => boolean
[nuts] => integer
[] => NULL
[fruits] => string
)

Related

PHP Group tabels [duplicate]

If 0 could be a possible key returned from array_search(), what would be the best method for testing if an element exists in an array using this function (or any php function; if there's a better one, please share)?
I was trying to do this:
if(array_search($needle, $haystack)) //...
But that would of course return false if $needle is the first element in the array. I guess what I'm asking is is there some trick I can do in this if statement to get it to behave like I want it? I tried doing these, but none of them worked:
$arr = array(3,4,5,6,7);
if(array_search(3, $arr) != false) //...
if(array_search(3, $arr) >= 0) //...
Appreciate the help.
This is the way:
if(array_search(3, $arr) !== false)
Note the use of the === PHP operator, called identical (not identical in this case). You can read more info in the official doc. You need to use it because with the use of the equal operator you can't distinguish 0 from false (or null or '' as well).
A better solution if you find the match and want to use the integer value is:
if (($pos = array_search(3, $arr)) !== false)
{
// do stuff using $pos
}
As an alternative to === and !==, you can also use in_array:
if (in_array($needle, $haystack))
As an alternative to ===, !==, and in_array(), you can use array_flip():
$arr = [3,4,5,6,7];
$rra = array_flip($arr);
if( $rra[3] !== null ):
var_dump('Do something, '.$rra[3].' exists!');
endif;
This is not fewer lines than the accepted answer. But it does allow you to get position and existence in a very human-readable way.
We want to find out if int 3 is in $arr, the original array:
array (size=5)
0 => int 3
1 => int 4
2 => int 5
3 => int 6
4 => int 7
array_flip creates a new array ($rra) with swapped key-value pairs:
array (size=5)
3 => int 0
4 => int 1
5 => int 2
6 => int 3
7 => int 4
Now we can verify the existence of int 3, which will (or will not be) a key in $rra with array_key_exists, isset, or by enclosing $rra[3]` in an if statement.
Since the value we are looking for could have an array key id of 0, we need to compare against null and not rely on evaluating 0 to false.
You can also make changes to the original array, should that be the use case, because if $rra[3] isn't null, $rra[3] will return what is the key (position 0, in this case) for the value in the original array.
if ( $rra[3] !== null ):
// evaluates to: unset( $array[0] );
unset( $arr[ $rra[3] ] );
endif;
This operation works just as well if you're working with an associative array.

why it returns empty value but of boolean type when no match is found

I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?
$arr =Array
(
0 => Array
(
'uid' => '100',
'name' => 'Sandra Shush'
),
1 => Array
(
'uid' => '5465',
'name' => 'Stefanie Mcmohn'
),
2 => Array
(
'uid' => '40489',
'name' => 'Michael'
)
);
$match = array_search('546',array_column($arr, 'uid'));
echo gettype($match);
If you take a look at array_search method description http://php.net/manual/ro/function.array-search.php it says: Returns the key for needle if it is found in the array, FALSE otherwise. There is your answer.
http://php.net/manual/en/function.array-search.php
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource and NAN).
array_search() function returns the key for needle if it is found in the array, FALSE otherwise. So when you are using gettype() on the return value, then it will return the type of FALSE i.e. BOOLEAN for unsuccessful search, otherwise INT index value.
your code is working , when array_search not found then return false and if gettype($match); then show boolean and if found then return index so in this case return integer
this is code which return
<?php
$arr =Array
(
0 => Array
(
'uid' => '100',
'name' => 'Sandra Shush'
),
1 => Array
(
'uid' => '5465',
'name' => 'Stefanie Mcmohn'
),
2 => Array
(
'uid' => '40489',
'name' => 'Michael'
)
);
$match = array_search('5465',array_column($arr, 'uid'));
echo gettype($match);
and output is: integer
this is normal example
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
for more information
http://php.net/manual/ro/function.array-search.php
array_search() returns FALSE when it cannot find the needle in the haystack.
The comparison is done using ==. This means, the values are converted to the same type, if needed. But their values must be the same after conversion. It doesn't match substrings.
echo(FALSE); doesn't print anything. The type of FALSE is boolean, indeed. And FALSE is == with the empty string (''), zero (0), the string that contain the number zero ('0') and other empty values.

make array of string to boolean

How can I make this into a boolean?
I tried this :
array('FALSE' => 'No', 'TRUE' => 'Yes')
I want the TRUE/FALSE to be treated as a boolean and not a string. How to do this?
When you put values in quotes, they are treated as strings. Simply use the true and false boolean keywords, eg
array(
false => 'No',
true => 'Yes'
)
Be mindful that PHP will auto-cast true to 1 and false to 0 in this case because
The (array) key can either be an integer or a string
This won't stop you being able to use $array[true] or $array[false] though.
See http://php.net/manual/language.types.array.php

Check to see if string is an integer (includes negative numbers) PHP

The function below checks if a string is an integer meaning it should only contain digits. But it does not check if number is negative (negative numbers should return true as well since they are integers).
function validateInteger($value)
{
//need is_numeric to avoid $value = true returns true with preg_match
return is_numeric($value) && preg_match('/^\d+$/', $value);
}
I ran tests and got results:
'12.5' => FALSE
12.5 => FALSE
'a125' => FALSE
'125a' => FALSE
'1a2.5' => FALSE
125 => TRUE
'abc' => FALSE
false => FALSE
true => FALSE
'false' => FALSE
'true' => FALSE
null => FALSE
'null' => FALSE
'1231' => TRUE
-1231 => FALSE (SHOULD RETURN TRUE)
'-1231' => FALSE (SHOULD RETURN TRUE)
I dont want to use itnval() < 0. I would prefer regular expression to check for negative numbers as well.
Thanks
EDIT:
I also have a function validateFloat that returns true if a given number is floating number meaning it can contain only digits and a dot. I need to apply same logic to this as well so that it returns true for negative floating numbers
is_int isn't good enough for you?
filter_var($input, FILTER_VALIDATE_INT) should have the same effect but also work on strings.
just use is_numeric(abs($val))

Checking if value exists in array with array_search()

If 0 could be a possible key returned from array_search(), what would be the best method for testing if an element exists in an array using this function (or any php function; if there's a better one, please share)?
I was trying to do this:
if(array_search($needle, $haystack)) //...
But that would of course return false if $needle is the first element in the array. I guess what I'm asking is is there some trick I can do in this if statement to get it to behave like I want it? I tried doing these, but none of them worked:
$arr = array(3,4,5,6,7);
if(array_search(3, $arr) != false) //...
if(array_search(3, $arr) >= 0) //...
Appreciate the help.
This is the way:
if(array_search(3, $arr) !== false)
Note the use of the === PHP operator, called identical (not identical in this case). You can read more info in the official doc. You need to use it because with the use of the equal operator you can't distinguish 0 from false (or null or '' as well).
A better solution if you find the match and want to use the integer value is:
if (($pos = array_search(3, $arr)) !== false)
{
// do stuff using $pos
}
As an alternative to === and !==, you can also use in_array:
if (in_array($needle, $haystack))
As an alternative to ===, !==, and in_array(), you can use array_flip():
$arr = [3,4,5,6,7];
$rra = array_flip($arr);
if( $rra[3] !== null ):
var_dump('Do something, '.$rra[3].' exists!');
endif;
This is not fewer lines than the accepted answer. But it does allow you to get position and existence in a very human-readable way.
We want to find out if int 3 is in $arr, the original array:
array (size=5)
0 => int 3
1 => int 4
2 => int 5
3 => int 6
4 => int 7
array_flip creates a new array ($rra) with swapped key-value pairs:
array (size=5)
3 => int 0
4 => int 1
5 => int 2
6 => int 3
7 => int 4
Now we can verify the existence of int 3, which will (or will not be) a key in $rra with array_key_exists, isset, or by enclosing $rra[3]` in an if statement.
Since the value we are looking for could have an array key id of 0, we need to compare against null and not rely on evaluating 0 to false.
You can also make changes to the original array, should that be the use case, because if $rra[3] isn't null, $rra[3] will return what is the key (position 0, in this case) for the value in the original array.
if ( $rra[3] !== null ):
// evaluates to: unset( $array[0] );
unset( $arr[ $rra[3] ] );
endif;
This operation works just as well if you're working with an associative array.

Categories