When PHP acquires a POST variable, does it automatically trim whitespace?

I have various text input fields on a homework webpage. I always make them a bit longer than the missing word or phrase.

Sometimes students will enter a space first, then begin writing. So I thought I might need to use trim() to get rid of the whitespace.

I entered all the answers for this week, but I put spaces before the word or phrase.

When I echo them, they all seem OK, no whitespace.

for ($i=1; $i <= 28; $i++) {
			echo ${"q$i"} . '<br>';
		}

Does PHP automatically trim whitespace when it receives a $_POST variable?

No, PHP does not automatically trim whitespace. However, HTML does not render more than one successive space character. If you view the source code of your rendered page, you should see all the spaces still there. You can view the source of your page by right clicking anywhere on the page in your browser and clicking “view source” or similar.

It’s important to remember this, as you’ll often find things hidden in the raw source that are hidden from you in the rendered output.

1 Like

Will this do the job??

for ($i=1; $i <= 15; $i++) {
               // catch empty variables
		    if (${"q$i"} == '') ${"q$i"} = 'X';
		    // get rid of possible white space with trim
		    $studentAnswers[] = trim(${"q$i"});
		    //echo ${"q$i"} . '<br>';
		}
Sponsor our Newsletter | Privacy Policy | Terms of Service