Jump to content

BEST PRACTICE: NULL vs ' '


ChenXiu

Recommended Posts

2 PART QUESTION (so I don't have to ask two questions 😀  )

1.)
My script has tons of PHP variables. Is it better to declare them all at the top of my page like this:
$cat = $words = $day = $lunch = $user = $address = $potato = $_SESSION["goodpeople"] = $dumbquestionList = $b = $hundredMoreVariables = "";
-or-
as needed, like this:
$cat = "";  if($day == 'Thursday') { $cat = 'time_to_feed'; }
$words = "";  $school = array('teachers'=>'boring','lunch'=>'free'); $words = $school['teachers'];
$_SESSION["goodpeople"] = ""; if($_SESSION["goodpeople"] == "" { $_SESSION["goodpeople"] = 'Gandhi'; }

2.)
What are the pros and cons of declaring variables as NULL and using " isset " versus declaring variables as "" and using ==
Example:

$cat = $words = $day = $lunch = $user = $address = NULL;
if( !isset($cat)) { $cat = 'black'; }.........................if(isset($day)) { $sleep = 'none'; }..............etc., etc.
-or-
$cat = $words = $day = $lunch = $user = $address = "";
if($cat == "") { $cat = 'black'; }............................ if($day != "") { $sleep = 'none'; }................etc., etc.

On my particular coding, I can use either the NULL/isset style, or, the ""/== style, with no errors or ill effects.... but something tells me the expert PHP coders prefer one over the other...

Thank you!!

Edited by ChenXiu
Link to comment
Share on other sites

It sounds like you're using procedural programming, in which case I'd go with defining the variables as you need them. If you're using OOP I recommend defining any class properties at top of the class, before the constructor - with PHP it's not technically necessary, but I find it cleaner.

As far as the use of isset() on null or == "", try empty(). empty() returns true if the variable is false (which null and "" equates to) or if the variable doesn't exist, so it covers all your angles with one check.

Link to comment
Share on other sites

Hmm! Method A or method B? When you are caught on the horns of a dilemma, look for a third way :)

Consider a sticky registration form. When first loaded the input values are blank, but if the validation fails you want to show the user's values. In this situation I like the "null coalesce" operator, ie "??".

Example

<?php

$fname = $_POST['fname'] ?? '';
$lname = $_POST['lname'] ?? '';
$email = $_POST['email'] ?? '';
$mobile = $_POST['mobile'] ?? '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD']=='POST') {
    
    $errors = [];                          // array for any error messages
    
    // validate input here
    
    if (!$errors) {
        // update database here
        header("location: thispage.php");  // reload page
        exit;
    }
    else {
        $error_message = 'yada yada';
    }
}
?>
<html>
<body>
    <form method='POST'>
        First name : <input type='text' name='fname' value='<?=$fname?>'> <br>
        Last name  : <input type='text' name='lname' value='<?=$lname?>'> <br>
        Email      : <input type='text' name='email' value='<?=$email?>'> <br>
        Mobile     : <input type='text' name='mobile' value='<?=$mobile?>'> <br>
        <br>
        <button type='submit'>Submit</button>
    </form>
    <?=$error_message?>
</body>
</html>

 

  • Like 1
Link to comment
Share on other sites

On 7/10/2021 at 7:19 AM, maxxd said:

It sounds like you're using procedural programming, in which case I'd go with defining the variables as you need them. If you're using OOP I recommend defining any class properties at top of the class, before the constructor - with PHP it's not technically necessary, but I find it cleaner.

As far as the use of isset() on null or == "", try empty(). empty() returns true if the variable is false (which null and "" equates to) or if the variable doesn't exist, so it covers all your angles with one check.

Excellent idea. I went through all of my code and switched all of the "if(isset($_POST["value"] && $_POST["value"] != NULL)" to "if(!EMPTY($_POST["value"]))" and it sure cleaned up my code! (However, there was 1 instance where using 'empty' messed things up though... I can't remember what it was right now, but it cleaned up 99% of my code 😀 )

 

On 7/10/2021 at 12:41 PM, Barand said:

look for a third way

Great idea! (I'm so used to the "which is better, A? or B?" game that I indeed forget to look outside the box for a third solution 😊)
So you must be psychic -- just a while ago I was working on the portion of my code that exactly matches your example.
I'm wrestling with ternary shorthand trying to figure out how to use "$errors .=" as a string rather than an array "$errors[ ]"
This doesn't work: $address = $_POST["address"] ?? $error .= ?: 'Address cannot be blank'; (I can't use $error .= in shorthand I guess)
(and I can't google it because .= isn't googlable :-)

1 hour ago, NotionCommotion said:

NULL provides more context

Thank you. And keeps my code cleaner (e.g instant error messages on un-needed variables. I probably still have at least a dozen unused variables ($someVariable = " ") that I have to find and clean up.

I never completely learned PHP and then decided to code. All my thousands of lines of code are all learning experiences that I botch up, then fix, but leave it there in case the fix makes things worse. All my code worked perfectly before Register Globals went out of fashion. Now nothing works 😀 everything is "isset-this" "empty-that" "null-this" "not-equal-that" and then trying to remember if it's better to do !== or just !=................ and now that I'm just starting to get a bit of a handle on all of that, someone comes along and invents "Public-this" "Private-that" "classes," and code with ->arrows in it ..... and now all the modern PHP has backslashes \something\this\that    OMG I'll never catch up to all the experts here 😀

Edited by ChenXiu
Link to comment
Share on other sites

2 hours ago, ChenXiu said:

However, there was 1 instance where using 'empty' messed things up though... I can't remember what it was right now,

empty() will see the string '0' as an empty value, so a numeric input where the user might need to enter '0' will have issues with using empty.   I tend to just use isset() if necessary, the != NULL second check you have is not necessary, isset() treats a NULL value as not set.

What I do is just side-step the whole "does it exist?" issue by ensuring my inputs always exist with the help of array_fill_keys.  A simple bit of code that looks like this:

$data = array_fill_keys(['all', 'my', 'inputs'], null);
$data = array_replace($data, array_intersect_key($_POST, $data));
//$data = array_map('emptyStringToNull', $data); // function I have to convert an empty string to null. Optional.

var_dump($data);

After that $data will always contain the three keys all, my, and inputs and they will either be the value entered in the form or null. 

2 hours ago, ChenXiu said:

This doesn't work: $address = $_POST["address"] ?? $error .= ?: 'Address cannot be blank';

As you discovered that doesn't work.  You can't combine your validation and definition like that.   Keep your validation separate.  I find  using an array over .= is easier/better.  You can implode your array in the end if you want a string value.

$name = $_POST['name'] ?? null;
$address = $_POST['address'] ?? null;
$errors = [];

if (!$name){
    $errors[] = 'Name is required.';
}

if (!$address){
	$errors[] = 'Address is required.';
}

echo implode("\r\n", $errors);

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.