Functions in PHP

Learn to create and use functions to organize and reuse your code


Descargar Funciones

What are Functions in PHP?

Definition

A function is a block of code that performs a specific task and can be reused multiple times in a program.

Advantages of using functions

  • Reusability: Write once, use many times
  • Organization: Break complex problems into smaller parts
  • Maintenance: Easy to modify and debug
  • Readability: Clearer, more understandable code

Basic syntax

<?php
function nombreFuncion($parametro1, $parametro2) {
    // Function code    return $resultado;
}
?>

📝 Practical Example - Functions with Forms

This example shows how to use functions to process form data.

Personal Information System

🔍 How the System Works

Processing with Redirection JavaScript

<?php
// Process formif ($_POST) {
    $destino = procesarOpcion($_POST['opcion']);
    if ($destino) {
        // Instead of header(), we use JavaScript        echo "<script>window.location.href = '$destino';</script>";
    }
}
?>

🎯 Types of Functions in PHP

Basic Functions

<?php
function saludar($nombre = "Guest") {
    return "¡Hola $nombre!";
}
echo saludar("Ana");
?>

Functions with Validation

<?php
function validarEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}
?>