TutsFx logo

PHP for Beginners: The Basics

Functions and Forms

2 min read Last updated 44 minutes ago

Functions bundle logic into reusable pieces, and forms are how PHP collects data.

Defining functions

php
<?php
function greet(string $name): string
{
    return "Hello, {$name}!";
}

echo greet("TutsFx"); // Hello, TutsFx!

PHP 8 supports type hints on parameters and return types.

Default values

php
<?php
function applyDiscount(float $price, float $percent = 10): float
{
    return $price * (1 - $percent / 100);
}

echo applyDiscount(100);      // 90
echo applyDiscount(100, 50);  // 50

Handling a form POST

html
<form method="post" action="subscribe.php">
    <label for="email">Email</label>
    <input type="email" name="email" id="email" required>
    <button type="submit">Subscribe</button>
</form>
php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);

    if ($email === false) {
        echo "Please provide a valid email address.";
    } else {
        echo "Thanks! We saved {$email}.";
    }
}

Validate, don't trust

Always filter_var or use a validation library. Storing raw POST data is how sites get hacked.

Calling functions in templates

php
<?php
function total(array $cart): float
{
    $sum = 0;
    foreach ($cart as $item) {
        $sum += $item['price'] * $item['qty'];
    }
    return $sum;
}
?>

<p>Cart total: $<?= total($cart) ?></p>

<?= ?> is shorthand for <?php echo ?> — keep it for short outputs.

Share:

We value your privacy

We use cookies to enhance your browsing experience, serve personalized ads, and analyze traffic. By clicking "Accept", you consent to our use of cookies. Read our Privacy Policy to learn more.