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!
Related
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.
I have a VERY simple code, I dont know what I am doing wrong. I am sending post variables with Ajax, there are 3 checkboxes (an array) name="options[]".. I am receiving the right array, if I check Option1, Option2 or Option3, I get the correct Array.. but when I try to check and confirm them with isset() or with array_key_exist() it does not give me the right answers.. For example, if I only check Option 1 and 3, I get the following in the POST
[options] => Array
(
[0] => option_one
[1] => option_two
)
I need to do some action only IF the certain key does NOT exist in the array.. I tried something like below..
if (array_key_exists("option_one", $_POST['options'])) {
echo "Option one exists";
} else {
echo "option one does not exist";
}
it returns flase results, then I tried using ! (not) before it, that returns the same result. Then I tried with isset($_POST['options']['option_one']) without any luck.. then I tried the following function to check again within the array..
function is_set( $varname, $parent=null ) {
if ( !is_array( $parent ) && !is_object($parent) ) {
$parent = $GLOBALS;
}
return array_key_exists( $varname, $parent );
}
and used it like this
if (is_set("option_one", $_POST['options'])) {
echo "Option one exists";
} else {
echo "option one does not exist";
}
nothing works, it simply returns false value. I tried with $_REQUEST instead if $_POST but no luck, I have read many threads that isset() or array_key_exists() returns false values.. What is the solution for this ? any help would be highly appreciated.. I am tired of it now..
regards
option_one is not a key in the array, it's a value. The key is 0. If anything, use:
in_array('option_one', $_POST['options'])
array_key_exists looks for the keys of the arrays. You are looking for the value. :)
What you want is
/**
* Check wheter parameter exists in $_POST['options'] and is not empty
*
* #param $needle
* #return boolean
*/
function in_options($needle)
{
if (empty($_POST['options']))
return false;
return in_array($needle, $_POST['options']);
}
Are you sure you are getting the correct information in your options[] array? If you clicked option 1 and option 3, shouldn't the array look something like this?
[options] => Array
(
[0] => option_one
[1] => option_three
)
Since isset() is a language construct and not a function, you may be able to rework the validation to be more efficient.
function in_options($needle)
{
//Checking that it is set and not NULL is enough here.
if (! isset($_POST['options'][0]))
return false;
return in_array($needle, $_POST['options']);
}
The function empty() works, but I think that $_POST['options'][0] only needs to be checked for isset() at this point.
I have encountered a very weird and concerning problem in some of my PHP code. A variable that I have returns true in an IF statement when it clearly should return false.
$pr = $_SESSION['fin_print_printer']; //this should equal 0
print $pr; //this returns 0, as it should
if($pr == "L"){
print "local";
} else {
print "serve";
}
print $pr; //this returns 0 again, as it should
This prints "local" in my script (in between the two zeros) and does not print "serve". With over 100,000 lines of code in my project, I've not experienced this issue yet, and now I can't figure out what is going on.
If I do if($pr === "L"), then it works as expected, but the above does not.
PHP is trying to typecast 'L' into an int, which results in 0.
intval('L'); // 0
Change your code into the following so it will take types into account:
if($pr === "L")
{
print "local";
}
else
{
print "serve";
}
Or manually typecast $pr to a string.
// You can also to (string)$pr ("0" instead of 0)
if(strval($pr) == "L")
{
print "local";
}
else
{
print "serve";
}
Maybe if you use typecasting (I did't check it):
if ( (string)$pr == "L" ) {
print "local";
} else {
print "serve";
}
Little known approach: You can also do the casting like
if ("L" == $pr) {
Because with loose comparisons, PHP casts the right value to the left value's type, and as you've already been made aware, while string(1)"L" is casted to int(0), int(0) is casted to string(1)"0".
How do I check if an array is undefined?
I am using isset and empty but both of them are not working for an undefined array.
This is my code:
if (isset($content['menu']['main'])){
echo 'there is menu';
}
use this code as specified by Rikesh and mimipc
$arr = array("menu"=>array("main"=>1));
if (is_array($arr) && array_key_exists('menu', $arr)) {
echo "array";
}
working example http://codepad.viper-7.com/Q3gTwn
Based on your code, I think you're looking for the function array_key_exists().
$content = array('menu'=>array());
echo isset($content);
>>> 1
echo array_key_exists('menu', $content);
>>> 1
if ( array_key_exists('main', $content['menu']) ) {
echo "Main menu exists";
} else {
echo "Main menu does not exist";
}
>>> Main menu does not exist
isset() will not work, because the variable $content is set, and the array may not be empty, so empty() will also not work. You want to see if the main key exists in the $content['menu'] array.
You can check if an array element exists with in_array:
in_array('one', array('two', 'three', 'four')); // false
And you can check array-indexes with array_key_exists:
array_key_exists('metallica', array('metallica' => 'worst than megadeth')); // true
With the isset function you only check if the array or variable is not equal to NULL and if it contains a value which can be interpreted as boolean True or False, integers larger than 0 and if the variable value (or array key/index/element) is not equal to NULL.
I usualy check if variable is set with: is_null, and it can be used to check if an array index or an element is defined within that same array.
EDIT:
You can also check if a variable is array with: (sizeof($something) > 0) or with: is_array function(s).
This question already has answers here:
How to check whether an array is empty using PHP?
(24 answers)
Closed 7 years ago.
I have the following code
<?php
$error = array();
$error['something'] = false;
$error['somethingelse'] = false;
if (!empty($error))
{
echo 'Error';
}
else
{
echo 'No errors';
}
?>
However, empty($error) still returns true, even though nothing is set.
What's not right?
There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:
$errors = array_filter($errors);
if (!empty($errors)) {
}
array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false.
Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.
You can also check it by doing.
if(count($array) > 0)
{
echo 'Error';
}
else
{
echo 'No Error';
}
Try to check it's size with sizeof if 0 no elements.
PHP's built-in empty() function checks to see whether the variable is empty, null, false, or a representation of zero. It doesn't return true just because the value associated with an array entry is false, in this case the array has actual elements in it and that's all that's evaluated.
If you'd like to check whether a particular error condition is set to true in an associative array, you can use the array_keys() function to filter the keys that have their value set to true.
$set_errors = array_keys( $errors, true );
You can then use the empty() function to check whether this array is empty, simultaneously telling you whether there are errors and also which errors have occurred.
array with zero elements converts to false
http://php.net/manual/en/language.types.boolean.php
However, empty($error) still returns true, even though nothing is set.
That's not how empty() works. According to the manual, it will return true on an empty array only. Anything else wouldn't make sense.
From the PHP-documentation:
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
function empty() does not work for testing empty arrays!
example:
$a=array("","");
if(empty($a)) echo "empty";
else echo "not empty"; //this case is true
a function is necessary:
function is_array_empty($a){
foreach($a as $elm)
if(!empty($elm)) return false;
return true;
}
ok, this is a very old question :) , but i found this thread searching for a solution and i didnt find a good one.
bye
(sorry for my english)
hi array is one object so it null type or blank
<?php
if($error!=null)
echo "array is blank or null or not array";
//OR
if(!empty($error))
echo "array is blank or null or not array";
//OR
if(is_array($error))
echo "array is blank or null or not array";
?>
I can't replicate that (php 5.3.6):
php > $error = array();
php > $error['something'] = false;
php > $error['somethingelse'] = false;
php > var_dump(empty($error));
bool(false)
php > $error = array();
php > var_dump(empty($error));
bool(true)
php >
exactly where are you doing the empty() call that returns true?
<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>
In PHP, even if the individual items within an array or properties of an object are empty, the array or object will not evaluate to empty using the empty($subject) function. In other words, cobbling together a bunch of data that individually tests as "empty" creates a composite that is non-empty.
Use the following PHP function to determine if the items in an array or properties of an object are empty:
function functionallyEmpty($o)
{
if (empty($o)) return true;
else if (is_numeric($o)) return false;
else if (is_string($o)) return !strlen(trim($o));
else if (is_object($o)) return functionallyEmpty((array)$o);
// If it's an array!
foreach($o as $element)
if (functionallyEmpty($element)) continue;
else return false;
// all good.
return true;
}
Example Usage:
$subject = array('', '', '');
empty($subject); // returns false
functionallyEmpty($subject); // returns true
class $Subject {
a => '',
b => array()
}
$theSubject = new Subject();
empty($theSubject); // returns false
functionallyEmpty($theSubject); // returns true