Don’t Use PHP in JS Condition Check
// todo
- php true vs false echo in js
- check if it’s true in php, with null, bool string object
- js if() with null, bool, string, int, object
Don’t use PHP in JS Condition Check.
<script>
if ('false') {
alert('hi');
}
</script>
Above code alerts “hi”. That’s alright.
<?php $demo = "false"; ?>
<script>
if (<?php echo $demo; ?>) {
alert('hi');
}
</script>
Above code has no alert
<?php $demo = "false"; ?>
<script>
if ('<?php echo $demo; ?>') {
alert('hi');
}
</script>
Above code alerts “hi”. That’s alright.
<?php $demo = "demo"; ?>
<script>
if ('<?php echo $demo; ?>') {
alert('hi');
}
</script>
Above code alerts “hi”.
<script>
<?php $demo = "true"; ?>
if (<?php $demo ; ?>) {
alert("hi");
}
</script>
no alert
<script>
<?php $demo = "true"; ?>
if (<?php echo $demo ; ?>) {
alert("hi");
}
</script>
Alert !
Conclusion:
- Try not to use php in js
- Use it the following way:
<?php if($first_condition): ?>
/*$first_condition is true*/
<?php elseif ($second_condition): ?>
/*$first_condition is false and $second_condition is true*/
<?php else: ?>
/*$first_condition and $second_condition are false*/
<?php endif; ?>