Syn Syn - 4 months ago 13
PHP Question

PHP switch not switching with integer

I have an HTML form and some PHP, but it always echo's "100 TEST" regardless of the case submitted. The default case works fine.

HTML:

<form class="page-search" action="page.php" method="post">
<input type="text" name="page" autofocus maxlength="3" placeholder="100" style="width: 50px;">
<input type="submit" style="visibility: hidden;">
</form>


PHP:

<?php
$pageid = isset($_POST['page']);

switch ($pageid) {

case '100':
echo '100 TEST';
break;

case '200':
echo '200 TEST';
break;

case '300':
echo '300 TEST';
break;

default:
echo 'DEFAULT';
break;

}
?>


Have I missed something really obvious? I'm kicking myself for needing to ask the question but can't seem to figure this one out!

Ali Ali
Answer

Change

$pageid = isset($_POST['page']);

To

$pageid = isset($_POST['page']) ? $_POST['page'] : 'default value if you need one';

Since the code is checking the result of the isset() method which will be a boolean, but the switch is interested in the $_POST['page'] value itself.


As mentioned in my comment here is an alternative for the example code:

echo isset($_POST['page']) ? $_POST['page'] . ' TEST' : 'DEFAULT';
Comments