This is one is confusing me.
I am trying to check if 2 vars are not in an array with an OR, but it returns the opposite results than the expected.
Does 2 !in_array, in conjunction with an OR, creates 2 negatives = positive?
The case:
$user->groups = array(2,13,15);
if ( !in_array(2, $user->groups) || !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
Since 2 is in the array, I expect the script to echo "In Array", but it echoes "Not in Array". If I remove the second !in_array after the OR, it echoes "In Array". If I change the OR with an AND, it echoes "In Array".
It doesn't make much sense, or I am just that confused at the moment. Can someone give some input?
The problem is you are using || instead of &&. What the logical OR (||) does is that it checks the first condition and if it is true then it does not test the other conditions in the if statement. Here is the revised code:
$user->groups = array(2,13,15);
if ( !in_array(2, $user->groups) && !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
Hope this helps!
Try this:
if ( !in_array(2, $user->groups) && !in_array(0, $user->groups) ) {
echo "Not in Array";
} else {
echo "In Array";
}
This will ensure that when both (&&) 0 and 2 are not in the array, it prints "Not in array"
As stated in my comment, you should be checking that the first value and the second value are not in the array: !in_array(2, $user->groups) && !in_array(0, $user->groups).
For two conditions, I would consider the following suggestion overkill but you may find it useful if you want to search for a larger number of values:
$arr = array(1,2,3);
$search = array(1,2);
$all_in = function($prev, $curr) use ($arr) {
return $prev && in_array($curr, $arr);
};
if (array_reduce($search, $all_in, true)) {
echo 'all values in $search are in $arr';
}
else {
echo 'some of the values in $search are not in $arr';
}
array_reduce applies the callback function $all_in to each of the values of the $search array and keeps track of a boolean value (initialised to true) that remains true as long as all the values are in the array $arr.
As I said, this approach isn't particularly useful if you're only looking for two values but one benefit is that you can easily add values to the $search array without changing any of the other code.
Related
I want to check if array is empty or not, i wrote few lines of code for it
if(array() == $myArray){
echo "Array";
}
or
if(array() === $myArray){
echo "Array";
}
I'm confused which one to use, as the second condition also checks type. But i think in the case of array we don't need to check their type.
Please anybody can suggest me which one to use.
you can check it by using empty() function like below
<?php
if(empty($myArray)) {
//condition
}
?>
if (! count($myArray)) {
// array is empty
}
Let php do its thing and check for booleans.
Use empty:
if (empty($myArray)) {
...
}
Try this :
<?php
$array = array();
if(empty($array))
{
echo "empty";
} else
{
echo "some thing!";
}
?>
It's always better to check first whether it is array or not and then it is empty or not. I always use like this because whenever I check only empty condition somewhere I don't get the expected result
if( is_array($myArray) and !empty($myArray) ){
.....
.....
}
<?php
if(empty($yourarry)){
}
OR
if(isset($yourarry)){
}
OR
if(count($yourarry)==0){
}
It depends:
Use count==0 if your array could also be an object implementing Countable
Use empty otherwise
array() == $myArray is unreadable, you should avoid it. You can see the difference between count and empty here.
I have an array and when I print the output like so print_r($userExists);
it returns Array ( ) I wrote this code to tell me if the array is empty or not:
if(isset($userExists)){
echo 'exists';
}else{
echo 'does not exists';
}
But regardless if the array is empty or not, it only returns exists What Am i doing wrong, when the array is populated, it looks like this Array ( [0] => Array ( [id] => 10 ) )
Use
if( !empty( $userExists ) ) {
echo 'exists';
}
else {
echo 'does not exists';
}
or
if( count( $userExists ) ) {
echo 'exists';
}
else {
echo 'does not exists';
}
However is safer to use empty() as if that variable doesn't exists your script will not stop due to exception while count() does.
isset is "not working"* here since this variable is setted (so exists) even if is empty.
So, basically, isset will
Determine if a variable is set and is not NULL.
Last but not least, if you want to know which is "better" for code optimization, I could tell you a little "secret": count() doesn't need to traverse the array each time to know how many elements will be there since, internally, it store the elements number (as you can see under), so every call to count() function results in O(1) complexity.
ZEND_API int zend_hash_num_elements(const HashTable *ht)
{
IS_CONSISTENT(ht);
return ht->nNumOfElements;
}
zend_hash_num_elements is called from count() (take a look here)
from php manual
*(not working as you wish/need)
use as below
if(isset($userExists) && count($userExists) > 0 ){
echo 'exists';
}else{
echo 'does not exists';
}
OR
You can check if the variable is an array and having some value
if(is_array($userExists) && count($userExists) > 0 ){
echo 'exists';
}else{
echo 'does not exists';
}
$userExists = array();
The variable exists, and it is set. That's what isset tests for.
What you want is:
if( $userExists) echo "exists";
You do not need an extra check for if!
if($array){
// Will execute only if there is any value inside of the array
}
By using if there is no need checking if any value is available!
you are using 'isset' for variables that might not exist like $_GET value or $_SESSION etc....
'empty' to check a string value
by php documentation empty works only in string and not arrays
can anyone explain why I can't see what's inside the array? I think it supposed to be able to have multiple numbers (subscriptions) so maybe that's why I'm having trouble? Here's the code.
$num = $_SESSION['subscription_ids'];
if(is_array($num))
{
print_r($num);
}
else
{
echo "not an array";
}
//Thanks DonnieM, yet It's spliting out "Array ( ) " no joke.
What is going on?
Your confusion apparently arises from the output of 1 for is_array.
is_array returns a boolean value (true or false). When outputting boolean values as text, true is represented as 1 and false as nothing (an empty string).
Therefore 1 just means yes, this is an array. It does not tell you how many elements there are in the array.
Is this what you mean ?
php > $a = array();
php > echo is_array($a);
1
php > print_r($a);
/* this is not empty, but an empty array */
Array
(
)
/* as long $a is initiate, it WILL NEVER return NULL */
php > var_dump($a);
array(0) {
}
/* but */
php > $a = array(null);
php > var_dump($a);
array(1) {
[0]=>
NULL
}
Hard to say off hand since I don't know what the value of $_SESSION['subscription_ids'] is. It looks to me that you are using the is_array function incorrectly. It returns a boolean value and you're just assigning it to a variable instead. Here is a link to the documentation:
http://php.net/manual/en/function.is-array.php
I would say structure your code like this:
$num = $_SESSION['subscription_ids'];
if(is_array($num))
{
print_r($num);
}
else
{
echo "not an array";
}
Hope this helps!
I'm having difficulty comparing the $_POST from a user input to a set of array values.
I've set the following variable ...
$response = $_POST['answer'];
... and selected a range of possible correct answers and stored them in an array ...
$solutions = array('answer1','answer2','answer3');
I've tried checking/comparing like this ...
if (value($response) !== ($solutions)
{$error['result'] = "Wrong answer.";}
I know it's the line if (value($response) !== ($solutions).
in_array() is your friend:
$correct = in_array($response, $solutions);
If you want to compare array values;
as harakiri wrote in_array() is your friend.
However if you want to compare array keys, you have to use;
array_key_exists()
I would like to warn you tho, if your array contains a lot of information checking it with in_array() will slow you down.
Instead you will have to go with isset() to check if it is set, it is much faster than in_array().
$answer = false;
foreach ($solutions as $sol)
{
if ($sol == $_POST['answer'])
{
$answer = $sol;
break;
}
}
if ($answer)
{
//GOOD
}
else
{
$error['result'] = "Wrong answer."
}
Hi lets say I've got this array:
$check_post = array(
$_POST["a_post"],
$_POST["b_post"],
$_POST["c_post"],
$_POST["d_post"],
$_POST["e_post"],
$_POST["f_post"],
$_POST["g_post"],
$_POST["h_post"],
$_POST["i_post"]
);
I want to check whether any elements of this array are repeated, so the best I got is this:
if (count(array_unique($check_post)) < count($check_post))
echo "Duplicate";
else
echo "NO Duplicate";
Which works fine except for the fact that if more that one textarea is left blank (which is allowed) it gives me FALSE.
What I want is to NOT consider the empty values of the array for the (count(array_unique())
BTW I have tried with empty() and with array_values($check_post) but I cant get around it.
Thanks in advance!! please ask for any needed clarification.
To remove all the empty values from the comparison you can add array_diff():
if (count(array_unique(array_diff($check_post,array("")))) < count(array_diff($check_post,array(""))))
Well the way you have it is fine, though as you say, you have a need to remove the empty entries first.
$non_empty_check_post = array_filter($check_post, create_function('$item', 'return !empty($item);');
if (count(array_unique($non_empty_check_post)) < count($non_empty_check_post)) {
echo "Duplicate";
} else {
echo "NO Duplicate";
}
Filter out the blanks from your array:
function no_blanks($val) {
// Do not use empty() here if you don't consider the string "0" as blank
return trim($val) !== '';
}
$check_post = array_filter($check_post, 'no_blanks');
if (count(array_unique($check_post)) < count($check_post))
echo "Duplicate";
else
echo "NO Duplicate";
if (count(array_unique(array_filter(function(x) {return !empty(x)}, $check_post)) < count($check_post))
echo "Duplicate";
else
echo "NO Duplicate";