isset() or array_key_exists() doesnt work with $_POST - php

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.

Related

Checking if array is empty or not doesn't seems to work

Simple array and simple check if is array or object .. yet page crashing when there is no array data instead of showing No. This is the array
$url=get_curl_content_tx("https://example.com");
$arr = json_decode($url, true);
if (is_array($arr['outputs']) || is_object($arr['outputs'])) {
echo 'Yes';
}
else {
echo 'No';
}
if I receive fail i.e. no data from the url and $arr['outputs'] is empty I've got blank page with
Undefined index: outputs
instead of No. Doesn't if (is_array($arr['outputs']) || is_object($arr['outputs'])) check if is array or no?
If there is data in $arr['outputs'] everything is fine.
You need to use isset or array_key_exists to check the key exists in the $arr array before referring to it.
if (isset($arr['outputs']) && is_array($arr['outputs'])) {
You want to access a non-existent array, which gives you an error, no matter what function you are using right before. To solve this, check first if the array exists with isset():
if(isset($arr)) {
// Just gets executed if the array exists ans isn't nulll
} else {
// Array is null or non-existend
}
and add then your code in the if-else.

Count array & in_array in one function

Is there a better/shorter way to perform the following:
$stock_array = array("soccer" => "0");
if (count($stock_array) == 1 && in_array('0', $stock_array)) {...}
I want to check if the array has 1 element, and the value is 0.
Thanks in advance
Based on your title, this provides if the count is one and its value is 0
$count = array_count_values($stock_array);
if ($count == array('0' => 1)) {
//something
}
Or you can also use array_filter() with empty(), if you are looking for a pre-function kind of answer: This will return True if all the values in the array are empty or 0.
if (empty(array_filter($stock_array))) {
//something
}
Yes, you can try using the following code.
if (array_search('0', array_values($stock_array)) == 0) {...}
But this doesn't tell if the array has only this element.
From your question, I can understand you are trying to do:
Check the length of array to be 1.
Check if the value exists in the array.
The solution I provided, checks if that's the first value of the array. But to check the length of array, you need to have another as well.

PHP if array is empty

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

Deep array !empty check in php

I need to check array value, but when array is empty, I get this: Error: Cannot use string offset as an array
if (!empty($items[$i]['tickets']['ticket'][0]['price']['eur'])) { //do something }
How to do it correctly?
You need to check if the variable is set, then if it is an array and then check if the array's element is set. The statements of the if will be executed in order and will break when one is false.
if(isset($items) && is_array($items) && isset($items[$i]['tickets']['ticket'][0]['price']['eur'])) {
//jep it's there
}
Or just try it (extra sipmle variant):
if (!isset($items[$i]['tickets']['ticket'][0]['price']['eur'])) {
// do action
}

PHP: testing for existence of a cell in a multidimensional array

I have an array with numerous dimensions, and I want to test for the existence of a cell.
The below cascaded approach, will be for sure a safe way to do it:
if (array_key_exists($arr, 'dim1Key'))
if (array_key_exists($arr['dim1Key'], 'dim2Key'))
if (array_key_exists($arr['dim1Key']['dim2Key'], 'dim3Key'))
echo "cell exists";
But is there a simpler way?
I'll go into more details about this:
Can I perform this check in one single statement?
Do I have to use array_key_exist or can I use something like isset? When do I use each and why?
isset() is the cannonical method of testing, even for multidimensional arrays. Unless you need to know exactly which dimension is missing, then something like
isset($arr[1][2][3])
is perfectly acceptable, even if the [1] and [2] elements aren't there (3 can't exist unless 1 and 2 are there).
However, if you have
$arr['a'] = null;
then
isset($arr['a']); // false
array_key_exists('a', $arr); // true
comment followup:
Maybe this analogy will help. Think of a PHP variable (an actual variable, an array element, etc...) as a cardboard box:
isset() looks inside the box and figures out if the box's contents can be typecast to something that's "not null". It doesn't care if the box exists or not - it only cares about the box's contents. If the box doesn't exist, then it obviously can't contain anything.
array_key_exists() checks if the box itself exists or not. The contents of the box are irrelevant, it's checking for traces of cardboard.
I was having the same problem, except i needed it for some Drupal stuff. I also needed to check if objects contained items as well as arrays. Here's the code I made, its a recursive search that looks to see if objects contain the value as well as arrays. Thought someone might find it useful.
function recursiveIsset($variable, $checkArray, $i=0) {
$new_var = null;
if(is_array($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable[$checkArray[$i]];
else if(is_object($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable->$checkArray[$i];
if(!isset($new_var))
return false;
else if(count($checkArray) > $i + 1)
return recursiveIsset($new_var, $checkArray, $i+1);
else
return $new_var;
}
Use: For instance
recursiveIsset($variables, array('content', 'body', '#object', 'body', 'und'))
In my case in drupal this ment for me that the following variable existed
$variables['content']['body']['#object']->body['und']
due note that just because '#object' is called object does not mean that it is. My recursive search also would return true if this location existed
$variables->content->body['#object']->body['und']
For a fast one liner you can use has method from this array library:
Arr::has('dim1Key.dim2Key.dim3Key')
Big benefit is that you can use dot notation to specify array keys which makes things simpler and more elegant.
Also, this method will work as expected for null value because it internally uses array_key_exists.
If you want to check $arr['dim1Key']['dim2Key']['dim3Key'], to be safe you need to check if all arrays exist before dim3Key. Then you can use array_key_exists.
So yes, there is a simpler way using one single if statement like the following:
if (isset($arr['dim1Key']['dim2Key']) &&
array_key_exists('dim3Key', $arr['dim1Key']['dim2Key'])) ...
I prefer creating a helper function like the following:
function my_isset_multi( $arr,$keys ){
foreach( $keys as $key ){
if( !isset( $arr[$key] ) ){
return false;
}
$arr = $arr[$key];
}
return $arr;
}
Then in my code, I first check the array using the function above, and if it doesn't return false, it will return the array itself.
Imagine you have this kind of array:
$arr = array( 'sample-1' => 'value-1','sample-2' => 'value-2','sample-3' => 'value-3' );
You can write something like this:
$arr = my_isset_multi( $arr,array( 'sample-1','sample-2','sample-3' ) );
if( $arr ){
//You can use the variable $arr without problems
}
The function my_isset_multi will check for every level of the array, and if a key is not set, it will return false.

Categories