let me explain my problem..
This is my array
$data['id']=1;
$data['name']='Bhavik';
$data['salary']=0;
$data['TA']=0;
before processing on the data I am checking whether the key is empty or not if it is empty then we have to neglect it.
like..
if(!empty($data['id']))
{
$responseData['id']=$data['id'];
}
if(!empty($data['name']))
{
$responseData['name']=$data['name'];
}
if(!empty($data['salary']))
{
$responseData['salary']=$data['salary'];
}
if(!empty($data['TA']))
{
$responseData['TA']=$data['TA'];
}
print_r(responseData);
it gives me only id and name
it considers 0 as empty
what if I want salary and TA with Zero value?
I can do it with checking whether the key is exists or not and the check whether it has any value or not but is there any other way.
I am not using key_exists just because if we pass array like $data['id] without any value still that condition will be true but it gives error bcoz it does not have any value while processing the data.
so any help will be appreciated.
Thank you
you can add second OR condition within IF condition statement like
if(!empty($a) || $a==0)
Try this hope it will solve your problem
You can use this function instead of empty:
function is_blank($value) {
return empty($value) && !is_numeric($value);
}
Treating the values as strings, check the string length with strlen() and the validity of characters inside it, in this case (from the description I assume all-digit values) - ctype_digit().
If you don't know whether the key exists, check that with isset().
You can check using strict compare
if(null!==$a){
//... 0 is passed as true value
}
Related
In laravel I have send the ajax response to the controller. there I have check the condition to check the count of the response geo as if(count($request['geo'])) and for some reason I want to check the condition if no count for geo as if(count($request['geo']) == 0).but its not working.
How to check the condition 'if no count for geo' in laravel
if $request['geo'] contains an array, then count($request['geo']) == 0 will be true for empty array [].
But if $request['geo'] contains a string (e.g. '[]') - it won't work and you can't use count() for strings. For checking empty strings you can use $request['geo'] == '' or !$request['geo']
Probably you need to check the type of value first, e.g. using is_array($request['geo'])
P.S. !$request['geo'] works for both - empty arrays and empty strings
You can check like this
if(empty($request['geo'])){
// your code
}
You can use php function gettype and count.
So you can use following code:
if(gettype($request['geo']) == 'array') {
if (count($request['geo']) == 0) {
// your code here
} else { // count > 0
// your other code here
}
}
Hope to helpful.
I face a problem like this:
$area="Dhaka";
isset($area); //returns true which is OK
isset($area['division']); //returns true why?
// actually, any array key of area returns true
isset($area['ANY_KEY']);//this is my question 1
isset($area['division']['zilla');//now it returns false.
//as I know it should returns false but why previous one was true.
Now if I do this:
$area['division'] = "Dhaka";
isset($area); // returns true which is OK
isset($area['division']); // returns true it's also OK
isset($area['ANY_KEY']); // returns false. I also expect this
isset($area['division']['ANY_KEY']); // returns true why? question #2
Basically both of my questions are the same.
Can anyone explain this?
As with every programming language in existence, a string is stored as an array of characters.
If I did:
$area = "Dhaka";
echo $area[0];
It would return D.
I could also echo the whole string by doing:
echo $area[0].$area[1].$area[2].$area[3].$area[4];
PHP will also type juggle a string into 0 when passed in a manner that accepts only integers.
So by doing:
echo $area['division'];
You would essentially be doing:
echo $area[0];
and again, getting D.
That's why isset($area['division']) returns a true value.
Why doesn't $area['foo']['bar'] (aka $area[0][0]) work? Because $area is only a single-dimension array.
The best approach to handle this problem when you're working with a variable that could either be a string or an array is to test with is_array() before trying to treat your variable as an array:
is_array($area) && isset($area['division'])
PHP lets you treat a string as an array:
$foo = 'bar';
echo $foo[1]; // outputs 'a'
So
$area['division']
will be parsed/executed as
$area[0];
(the keys cannot be strings, since it's not REALLY an array, so PHP type-converts your division string by its convert-to-int rules, and gives 0), and evaluate to the letter D in Dhaka, which is obviously set.
Okay, here's a solution rather than explaining why isset isn't going to work properly.
You want to check if an array element is set based on it's index string. Here's how I might do it:
function isset_by_strkey($KeyStr,$Ar)
{
if(array_key_exists($KeyStr,$Ar))
{
if(strlen($Ar[$KeyStr]) > 0 || is_numeric($Ar[$KeyStr] !== FALSE)
{
return TRUE;
}
return FALSE;
}
}
isset_by_strkey('ANY_KEY',$area); // will return false if ANY_KEY is not set in $area array and true if it is.
The best way to access a linear array in php is
// string treated as an linear array
$string= "roni" ;
echo $string{0} . $string{1} . $string{2} . $string{3};
// output = roni
It is expected behaviour.
PHP Documentation covers this
You can try empty() instead.
If it is returning true for keys that do not exist there's nothing you can do; however, you can make sure that it doesn't have a negative effect on your code. Just use array_key_exists() and then perform isset() on the array element.
Edit: In fact, using array_key_exists() you shouldn't even need isset if it is misbehaving just use something like strlen() or check the value type if array_key_exists returns true.
The point is, rather than just saying isset($Ar['something']) do:
if(array_key_exists('something',$Ar) )
and if necessary check the value length or type. If you need to check the array exists before that of course use isset() or is_array() on just the array itself.
I am reading file. I read all data in $part. it is working fine but issue arise when i use empty function. It should display NULL but it is not showing NULL.
My code is as follows:
echo "\nParts------------".$parts[$r]."\n";
echo "\nParts---Size---------".strlen($parts[$r])."\n";
var_dump($parts[$r]);
// $parts[$r]=trim($parts[$r],' ');
//$parts[$r]=str_replace('""','',($parts[$r]));
if(empty($parts[$r]))
{
$entryarray[$c][$c2]='NULL';
}
else if(strlen($parts[$r])<1) //removing special characters
{
$entryarray[$c][$c2]='NULL';
// array_push($entryarray[$c]);
$valueArray=$valueArray.",".'NULL';
}
when i vardump($part) then it is showing its length is 2 instead of 0.
How to display it NULL. i cant write check as if(strlen($parts<2)) cause there is data in file which has lenght less then 2.
I think you meant to use isset instead.
$foo = array("a", "b");
isset($foo[2]); // false
The empty function check if is null or empty string or 0 or something like that.
If you want to chack if is null, i recommend u to use "is_null()"
To check if a key is on array use
array_key_exists($key,$array);
This is honestly the most finicky and inept language I've ever coded in. I'll be glad when this project is good and over with.
In any case I have to us PHP so here's my question.
I have an Array named $form_data as such:
$form_data = array
('trav_emer_med_insur',
'trav_emer_single',
'trav_emer_single_date_go',
'trav_emer_single_date_ba',
'trav_emer_annual',
'trav_emer_annual_date_go',
'trav_emer_extend',
'trav_emer_extend_date_go',
'trav_emer_extend_date_ef',
'trav_emer_extend_date_ba',
'allinc_insur',
'allinc_insur_opt1',
'allinc_single_date_go',
'allinc_single_date_ba',
'allinc_insur_opt2',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'cancel_insur',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'visitor_insur',
'country_select',
'visitor_supervisa',
'visitor_supervisa_date_go',
'visitor_supervisa_date_ba',
'visitor_student',
'visitor_student_date_go',
'visitor_student_date_ba',
'visitor_xpat',
'visitor_xpat_date_go',
'visitor_xpat_date_ba',
'txtApp1Name',
'txtApp2Name',
'txtApp1DOB',
'txtApp2DOB',
'txtApp1Add',
'txtApp1City',
'selprov',
'txtApp1Postal',
'txtApp1Phone',
'txtApp1Ext',
'txtApp1Email',
'conpref', );
These are the names of name="" fields on an HTML form. I have verified that ALL names exist and have a default value of '' using var_dump($_POST).
What I want to do is very simple, using the $form_data as reference do this:
create a new array called $out_data which can handle the data to display on a regurgitated form.
The structure of $out_data is simple the key will be the name of the element from the other array $out_data[txtApp1Name] for example, and then the value of that key will be the value.
Now what I want is to first check to see if every name="" is set or not, to eliminate errors and verify the data. Then regardless of whether it is set or not, create its placeholder in the $out_data array.
So if $_POST[$form_data[1]] (name is 'trav_emer_single') is not set create an entry in $out_data that looks like this $out_data([trav_emer_single] => "NO DATA")
If $_POST[$form_data[1]] (name is 'trav_emer_single') is set create and entry in $out_data that looks like this: $out_data([trav_emer_single] => "whatever the user typed in")
I have tried this code:
$out_data = array();
$count = count($form_data);
for( $i = 0; $i < $count; $i++ )
{
if(!isset($_POST[$form_data[$i]])) {
$out_data[$form_data[$i]] = "NO_DATA";
}
else {
$out_data[$form_data[$i]] = $_POST[$form_data[$i]];
}
}
Now this code technically is working, it is going through the array and assigning values, but it is not doing so properly.
I have hit submit on the form with NOTHING entered. Therefore every item should say "NO_DATA" on my regurgitated output (for user review), however only some items are saying it. All items I have confirmed have name="" and match the array, and have nothing entered in them. Why is "NO_DATA" not being assigned to every item in the array?
Also of note, if I fill in the form completely $out_data is fully and correctly populated. What is the problem with !isset? I've tried doing $_POST[$form_data[$i]] == '' which does put no_data in every instance of no data, however it throws an 'undefined index' warning for every single item on the page whether I write something in the box or not.
Really I just want to know WTF is going on, the dead line for this project is closing fast and EVERY step of the PHP gives me grief.
As far as I can tell by reading around my code is valid, but refuses to execute as advertised.
If you need more code samples please ask.
Really befuddled here, nothing works without an error, help please.
Thanks
-Sean
Instead of checking !isset(), use empty(). If the form posts an empty string, it will still show up in the $_POST as an empty string, and isset() would return TRUE.
I've replaced your incremental for loop with a foreach loop, which is almost always used in PHP for iterating an array.
$out_data = array();
foreach ($form_data as $key) {
if(empty($_POST[$key])) {
$out_data[$key] = "NO_DATA";
}
else {
$out_data[$key] = $_POST[$key];
}
}
PHP's isset returns TRUE unless the variable is undefined or it is NULL. The empty string "" does not cause it to return FALSE. empty() will do exactly what you need, though.
http://php.net/manual/en/function.isset.php
isset() will return FALSE if testing a variable that has been set to
NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP
NULL constant.
Returns TRUE if var exists and has value other than NULL, FALSE
otherwise.
I am working on a signup form, I am using PHP and on my processing part I run some code, if a submitted item fails I then add it to an errors array.
Below is a snip of the code, I am at the point where I need to find the best method to determine if I should trigger an error.
So if there is a value set in the error array then I need to redirect and do some other stuff.
I was thinking of using isset or else is_array but I don't think that is the answer since I set the array using **$signup_errors = array()** wouldn't this make the is_array be true?
Can anyone suggest a good way to do this?
//at the beginning I set the error array
$signup_errors = array();
// I then add items to the error array as needed like this...
$signup_errors['captcha'] = 'Please Enter the Correct Security Code';
if ($signup_errors) {
// there was an error
} else {
// there wasn't
}
How does it work? When converting to boolean, an empty array converts to false. Every other array converts to true. From the PHP manual:
Converting to boolean
To explicitly convert a value to
boolean, use the (bool) or (boolean)
casts. However, in most cases the cast
is unncecessary, since a value will be
automatically converted if an
operator, function or control
structure requires a boolean argument.
See also Type Juggling.
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
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
You could also use empty() as it has similar semantics.
Perhaps empty()?
From Docs:
Return Values
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 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Check if...
if(count($array) > 0) { ... }
...if it is, then at least one key-value pair is set.
Alternatively, check if the array is not empty():
if(!empty($array)) { ... }
Use array_filter if you already have keys, but want to check for non-boolean evaluated values.
<?php
$errors = ['foo' => '', 'bar' => null];
var_dump(array_filter($errors));
$errors = ['foo' => 'Oops', 'bar' => null];
var_dump(array_filter($errors));
Output:
array(0) {
}
array(1) {
["foo"]=>
string(4) "Oops"
}
Use:
<?php
if(array_filter($errors)) {
// Has errors
}
You could check on both the minimum and maximum values of the array, in this case you can have a large array filled with keys and empty values and you don't have to iterate through every key-value pair
if(!min($array) && !max($array)) { ... }
The language construct isset(), is for testing to see if variables and array elements are set and not NULL. Using is_array() would tell you if the argument you supply to it is an array. Thus, I do not think using isset() or is_array() would give you the correct and desired result that you are seeking.
The code:
$signup_errors = array();
means that ...
is_array($signup_errors);
would return true. However, this does not mean that the Boolean language rules of PHP would evaluate....
if($signup_errors)
{
//*Do something if $signup_errors evaluates to true*;
}
as true, unless some elements are added to it. When you did this,
$signup_errors['captcha'] = 'Please Enter the Correct Security Code';
you fulfilled the PHP language requirement for the array above to evaluate to true.
Now, if for some reason you wanted, or needed, to use isset() on the array elements in the future, you could. But, the conditional statement above is enough for you this case.
I should add an obvious answer here. If you initialise your error array as an empty array. And later want to check if it is no longer an empty array:
<?php
$errors = [];
if($errors !== [])
{
// We have errors.
}