I've got a function that is used in a loop, however it is not working at all, here's example of my code
function is_banned_category($a) {
if(!is_array($a)) {
echo "returning false <Br/>";
return false;
}
$banned_list = array(
'Shopping',
'Product Info'
);
foreach($a as $cat) {
if(array_search($cat,$banned_list)) {
$return = true;
} else {
echo "Not found in:'{$cat}' <br/>";
}
}
return $return;
}
$a = array('Shopping');
if(is_banned_category($a)) {
echo "Item will not be added as it's in banned category";
}
Which would produce:
Item will not be added as it's in banned category
Am I missing something obvious here? It works with "Product Info" but not "Shopping"?
array_search($cat,$banned_list) returns 0, witch causes expression to evaluate to false. use in_array() or evaluate using Identical Operator ===
array_search returns the key of array value if exist, so in your case
array key of Shopping is "0"
if(array_search($cat,$banned_list)) // return 0
So else part will be worked
The function array_search will return the index of the occurrence if found (which could be 0, which evaluates to false), or else false if not found, so you must use
if(array_search($cat, $banned_list) !== false) {
[.. do your stuff .. ]
}
to perform the check, or else you could do
if(in_array($cat, $banned_list)) {
[.. do your stuff .. ]
}
which, IMHO, is a little bit cleaner.
Related
This is my array in PHP:
$arr['key1']='value1';
$arr['key2']='value2';
$arr['key3']='value3';
$arr['key4']='value4';
$arr['key5']='value5';
$arr['key6']='value6';
I would like to test if a key is in the array. Is this function the correct way to proceed?
function isKeyInArray($key, $arr) {
if(isset($arr[$key]))
return true;
else
return false;
}
What I expect is that:
isKeyInArray('key3', $arr) // return true
isKeyInArray('key9', $arr) // return false
Many thanks in advance.
You can use array_key_exists.
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (array_key_exists("Volvo",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
See http://php.net/manual/en/function.array-key-exists.php
Use array_key_exists
if(array_key_exists('key6',$arr))
echo "present";
else
echo "not present";
Using isset() is good if you consider that null is not a suitable value. Also isset is faster than array_key_exists.
$a = [ 'one' => 1, 'two' => null ];
isset($a['one']); // true
isset($a['two']); // false
array_key_exists('two', $a); // true
Use php function array_key_exists('key3', $a);
First google your need and only after that you can use your own function. This will save lots of your time.
i have this array:
include("config.php");
$start = "2014-06-20 08:00:00";
$data = mysql_query ("select * from evenement WHERE start = '$start'");
$zaznam = mysql_fetch_array ($data);
while($zaznam = mysql_fetch_array ($data))
{
$arr2[] = $zaznam["resourceId"]; //store query values in second array
}
If i echo $arr2 i get this:
Array ( [0] => STK1 )
now i make condition for array_search:
if (array_search('STK1', $arr2)) {
echo "Arr2 contains STK1 <br>";
}
else {
echo "Arr2 not contains STK1 <br>";
}
but i get this Arr2 not contains STK1
how it is possible? What im doing wrong?
That is totally correct behaviour for PHP.
The documention for the return value says:
Returns the key for needle if it is found in the array, FALSE otherwise.
In your case you are getting 0 which also evaluates to false in an if.
You have to check if the value is not false using the !== operator.
if (array_search('STK1', $arr2) !== false) {
echo "Arr2 contains STK1 <br>";
}
else {
echo "Arr2 not contains STK1 <br>";
}
From the array_search documentation:
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.
array_search is returning 0 because it found a match at index 0 of the array. This is evaluating to false.
Instead try:
if (array_search('STK1', $arr2) !== false) {
echo "Arr2 contains STK1 <br>";
}
else {
echo "Arr2 not contains STK1 <br>";
}
I know this question has been asked before but I haven't been able to get the provided solutions to work.
I'm trying to check if the words in an array match any of the words (or part of the words) in a provided string.
I currently have the following code, but it only works for the very first word in the array. The rest of them always return false.
"input" would be the "haystack" and "value" would be the "needle"
function check($array) {
global $input;
foreach ($array as $value) {
if (strpos($input, $value) !== false) {
// value is found
return true;
} else {
return false;
}
}
}
Example:
$input = "There are three";
if (check(array("one","two","three")) !== false) {
echo 'This is true!';
}
In the above, a string of "There is one" returns as true, but strings of "There are two" or "There are three" both return false.
If a solution that doesn't involve having to use regular expressions could be used, that would be great. Thanks!
The problem here is that check always returns after the first item in $array. If a match is found, it returns false, if not, it returns true. After that return statement, the function is done with and the rest of the items will not be checked.
function check($array) {
global $input;
foreach($array as $value) {
if(strpos($input, $value) !== false) {
return true;
}
}
return false;
}
The function above only returns true when a match is found, or false when it has gone through all the values in $array.
strpos(); is totally wrong here, you should simply try
if ($input == $value) {
// ...
}
and via
if ($input === $value) { // there are THREE of them: =
// ...
}
you can even check if the TYPE of the variable is the same (string, integer, ...)
a more professional solution would be
in_array();
which checks for the existance of the key or the value.
The problem here is that you're breaking out of the function w the return statement..so u always cut out after the first comparison.
you should use in_array() to compare the array values.
function check($array) {
global $input;
foreach ($array as $value) {
if (in_array($value,$input))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}
}
}
You're returning on each iteration of $array, so it will only run once. You could use stristr or strstr to check if $value exists in $input.
Something like this:
function check($array) {
global $input;
foreach ($array as $value) {
if (stristr($input, $value)) {
return true;
}
}
return false;
}
This will then loop through each element of the array and return true if a match is found, if not, after finishing looping it will return false.
If you need to check if each individual item exists in $input you'd have to do something a little bit different, something like:
function check($array) {
global $input;
$returnArr = array();
foreach ($array as $value) {
$returnArr[$value] = (stristr($input, $value)) ? true : false;
}
return $returnArr;
}
echo '<pre>'; var_dump(check($array, $input)); echo '</pre>';
// outputs
array(3) {
["one"]=>
bool(false)
["two"]=>
bool(false)
["three"]=>
bool(true)
}
The reason your code doesnt work, is because you are looping through the array, but you are not saving the results you are getting, so only the last result "counts".
In the following code I passed the results to a variable called $output:
function check($array) {
global $input;
$output = false;
foreach ($array as $value) {
if (strpos($input, $value) != false) {
// value is found
$output = true;
}
}
return $output;
}
and you can use it like so:
$input = "There are two";
$arr = array("one","two","three");
if(check($arr)) echo 'this is true!';
I have a question, how do I put a condition for a function that returns true or false, if I am sure that the array is empty, but isset() passed it.
$arr = array();
if (isset($arr)) {
return true;
} else {
return false;
}
In this form returns bool(true) and var_dump shows array (0) {}.
If it's an array, you can just use if or just the logical expression. An empty array evaluates to FALSE, any other array to TRUE (Demo):
$arr = array();
echo "The array is ", $arr ? 'full' : 'empty', ".\n";
Sometimes it is suggested instead of just if'ing the array variable like:
if (!$array) {
// empty
}
to write out:
if (empty($array)) {
// empty
}
for readability reasons. Compare empty(php) language construct.
The PHP manually nicely lists what is false and not.
Use PHP's empty() function. It returns true if there are no elements in the array.
http://php.net/manual/en/function.empty.php
Use empty() to check for empty arrays.
if (empty($arr)) {
// it's empty
} else {
// it's not empty
}
You can also check to see how many elements are in the array via the count function:
$arr = array();
if (count($arr) == 0) {
echo "The array is empty!\n";
} else {
echo "The array is not empty! It has " . count($arr) . " elements!\n";
}
use the empty property as
if (!empty($arr)) {
//do what u want if its not empty
} else {
//do what if its empty
}
I have an array
$data = array( 'a'=>'0', 'b'=>'0', 'c'=>'0', 'd'=>'0' );
I want to check if all array values are zero.
if( all array values are '0' ) {
echo "Got it";
} else {
echo "No";
}
Thanks
I suppose you could use array_filter() to get an array of all items that are non-zero ; and use empty() on that resulting array, to determine if it's empty or not.
For example, with your example array :
$data = array(
'a'=>'0',
'b'=>'0',
'c'=>'0',
'd'=>'0' );
Using the following portion of code :
$tmp = array_filter($data);
var_dump($tmp);
Would show you an empty array, containing no non-zero element :
array(0) {
}
And using something like this :
if (empty($tmp)) {
echo "All zeros!";
}
Would get you the following output :
All zeros!
On the other hand, with the following array :
$data = array(
'a'=>'0',
'b'=>'1',
'c'=>'0',
'd'=>'0' );
The $tmp array would contain :
array(1) {
["b"]=>
string(1) "1"
}
And, as such, would not be empty.
Note that not passing a callback as second parameter to array_filter() will work because (quoting) :
If no callback is supplied, all entries of input equal to FALSE (see
converting to boolean) will be removed.
How about:
// ditch the last argument to array_keys if you don't need strict equality
$allZeroes = count( $data ) == count( array_keys( $data, '0', true ) );
Use this:
$all_zero = true;
foreach($data as $value)
if($value != '0')
{
$all_zero = false;
break;
}
if($all_zero)
echo "Got it";
else
echo "No";
This is much faster (run time) than using array_filter as suggested in other answer.
you can loop the array and exit on the first non-zero value (loops until non-zero, so pretty fast, when a non-zero value is at the beginning of the array):
function allZeroes($arr) {
foreach($arr as $v) { if($v != 0) return false; }
return true;
}
or, use array_sum (loops complete array once):
function allZeroes($arr) {
return array_sum($arr) == 0;
}
#fireeyedboy had a very good point about summing: if negative values are involved, the result may very well be zero, even though the array consists of non-zero values
Another way:
if(array_fill(0,count($data),'0') === array_values($data)){
echo "All zeros";
}
Another quick solution might be:
if (intval(emplode('',$array))) {
// at least one non zero array item found
} else {
// all zeros
}
if (!array_filter($data)) {
// empty (all values are 0, NULL or FALSE)
}
else {
// not empty
}
I'm a bit late to the party, but how about this:
$testdata = array_flip($data);
if(count($testdata) == 1 and !empty($testdata[0])){
// must be all zeros
}
A similar trick uses array_unique().
You can use this function
function all_zeros($array){//true if all elements are zeros
$flag = true;
foreach($array as $a){
if($a != 0)
$flag = false;
}
return $flag;
}
You can use this one-liner: (Demo)
var_export(!(int)implode($array));
$array = [0, 0, 0, 0]; returns true
$array = [0, 0, 1, 0]; returns false
This is likely to perform very well because there is only one function call.
My solution uses no glue when imploding, then explicitly casts the generated string as an integer, then uses negation to evaluate 0 as true and non-zero as false. (Ordinarily, 0 evaluates as false and all other values evaluate to true.)
...but if I was doing this for work, I'd probably just use !array_filter($array)