empty function not working correctly - php

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);

Related

How to match a variable with value in double array

i have a problem like the following sample code :
$code='100'; //$maybe $code='0' or $code='1' ... i just set a number as an sample
$xx=array(
'0'=>array(a,b,c),
'1'=>array(d,e,f),
........
'100'=>array(aa,bb,cc)
);
I want find $code in array :
if($code==$xx['$code']){
echo $xx['code'][0]; //if i want get the value 'aa'
}
But it seems like $xx['$code'] doesn't work.
Do anyone know the right way to solve it?
Firstly you need to use array_key_exists for getting within if condition and then after you can use it simply like as
if(array_key_exists($code,$xx)){
echo $xx[$code][0];
}
or can simply use isset instead like as
if(isset($xx[$code])){
echo $xx[$code][0];
}
you shouldn't use single quotations here,
when filling displaying a variable either use without quotations or put it between double "" try $xx[$code] or $xx["$code"]
Use isset OR !empty to check key exist in array or not. It will also check that key has valid value.
if(isset($xx[$code])){
echo $xx[$code][0];
}
OR
if(!empty($xx[$code])){
echo $xx[$code][0];
}
if($code==$xx['$code']){
echo $xx[$code][0]; //if i want get the value 'aa'
}
If you use '$code' the content of $code will not be checked as '' interpret everything as a string and won't look a variables in it.
You can't sace 'code' either, as code is only the name of the variable you use.

how to enter '0' with checking the key is not empty?

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
}

isset() returns true from a string variable accessed as an array with any key

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.

In PHP, can I differentiate the result of intval(null) from intval("0")?

I get input values via POST, some of them might be ID's referring to other things, and some start at 0. When choosing something with ID 0, or something without a value, is there a method like intval() that returns something more helpful than 0 on failure to parse? Or can I somehow differentiate the result of intval() from the failure to parse?
Example:
echo intval(null); // 0
echo intval("0"); // 0
You can use the filter_var() function to determine the difference:
filter_var(null, FILTER_VALIDATE_INT);
// false
filter_var('0', FILTER_VALIDATE_INT);
// int(0)
You can also add flags to specifically accept hexadecimal and octal values, but I wouldn't recommend that for your case.
Btw, in the more likely case that the variable comes from $_POST, you can also use filter_input():
if (is_int($nr = filter_input(INPUT_POST, 'nr', FILTER_VALIDATE_INT))) {
// $nr contains an integer
}
The reason I'm using is_int() on the result of filter_input is because when nothing is posted, null is returned; using is_int() guards against this issue.
Edit
If the question is really just about null vs '0' you can just compare $var !== null:
if (!is_null($var)) {
// $var is definitely not null
// but it might also be an object, string, integer, float even, etc.
}
You could first check if its a number:
is_numeric($val);
Ok, now go for the solution.
preg_match('/^\d+$/','0') //is true
preg_match('/^\d+$/',NULL) //is false

PHP isset not working properly on form, with loops and arrays

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.

Categories