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
Related
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.
My project is in cakePHP but I think this is an aspect of native PHP that I am misunderstanding..
I have an afterFind($results, $primary = false) callback method in my AppModel. On one particular find if I debug($results); I get an array like this
array(
'id' => '2',
'price' => '79.00',
'setup_time' => '5',
'cleanup_time' => '10',
'duration' => '60',
'capacity' => '1',
'discontinued' => false,
'service_category_id' => '11'
)
In my afterFind I have some code like this:
foreach($results as &$model) {
// if multiple models
if(isset($model[$this->name][0])) {
....
The results of the find are from my Service model so inserting that for $this->name and checking if(isset($model['Service'][0])) should return false but it returns true? if(isset($model['Service'])) returns false as expected.
I am getting the following PHP warning:
Illegal string offset 'Service'
so what's going on here? why does if(isset($model['Service'][0])) return true if if(isset($model['Service'])) returns false?
UPDATE:
I still don't know the answer to my original question but I got around it by first checking if $results is a multidimensional array with
if(count($results) != count($results, COUNT_RECURSIVE))
Use array_key_exists() or empty() instead of isset(). PHP caches old array values strangely. They have to be manually unset using unset()
isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.
String offsets provide a mechanism to use strings as if they were an array of characters:
$string = 'abcde';
echo $string[2]; // c
$model is indeed a string for all keys except discontinued.
As for the isset($model['Service'][0]) return value, I'm a bit surprised. This is a simplified test case:
$model = '2';
var_dump(isset($model['Service'])); // bool(false)
var_dump(isset($model['Service'][0])); // bool(true)
There must be a reason somewhere. Will have a dig..
I have an array that looks something like
array (size=7)
'car_make' => string 'BMW' (length=3)
'car_model' => string 'M3' (length=2)
'car_year' => string '2001' (length=4)
'car_price' => string '10000' (length=5)
'car_kilometers' => string '100000' (length=6)
'paint' => string 'black' (length=5)
'tires' => string 'pirelli' (length=7)
So basically there are a few base items in it that start with car_ and then a few extras.
I'm trying to search for each key that isn't car_* so paint and tires in this case. So I'm doing something like
foreach($_SESSION['car'][0] as $key=>$value)
{
if($key != preg_match('/car_.*/', $key))
{
echo 'Match';
}
}
Which I expected to echo out 2 Matches because of the 2 non car_ keys. Instead, this echos out 5 for the car_ keys.
But when I do
if($key == preg_match('/car_.*/', $key))
It echoes out 2 Matches for the 2 non car_ keys.
Where am I messing up or misunderstanding?
preg_match docs say about its return values:
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
So this wouldn't have worked in the first place.
I would use:
if ( substr($key, 0, 4) === "car_" )
...which is much less expensive as an operation than preg_match anyway.
According the documentation preg_match returns true when matching and false when not. So it appears that you are having some fun with PHP's type casting.
So rather than comparing the value you should check
if(true === preg_match('/car_.*/', $key))
This should take care of it.
Also, per the documentation:
Do not use preg_match() if you only want to check if one string is
contained in another string. Use strpos() or strstr() instead as they
will be faster.
Which would be:
if(false === str_pos('car_', $key))
From http://php.net/manual/en/function.preg-match.php
Return Values
preg_match() returns 1 if the pattern matches given subject, 0 if it
does not, or FALSE if an error occurred.
So you should compare it to 1 or to 0, not to a string.
The reason why your code was working but backwards is because comparing a number to a string produces interesting results:
From http://php.net/manual/en/types.comparisons.php
1 == "" is FALSE
0 == "" is TRUE
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))
$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
)