Introduction to PHP language

php introduction

PHP is a powerful and beginner-friendly language, especially for web development.
Understanding its core components like variables, functions, arrays, and control structures will give you a strong foundation to build dynamic and interactive websites. Once you grasp these basics, you'll be ready to explore more advanced features such as object-oriented programming and database management in PHP.

PHP tags

The most basic component of any PHP script is the PHP tag. PHP code is written within special tags to differentiate it from HTML. The opening and closing tags look like this:


    <?php
// PHP code goes here
?> 
  

PHP Syntax

PHP scripts are usually embedded in HTML and start with <?php and end with ?>. Inside these tags, you can write PHP code that will be executed on the server before the HTML is sent to the browser. Example:


<?php
echo "Hello, World!";
?>
 

Variables

Variables in PHP are used to store data that can be used and manipulated later. They are represented by a dollar sign ($) followed by the variable name. PHP is a loosely typed language, meaning you don’t need to specify the data type of a variable (like integer, string, etc.).
Example:


<?php
$name 
"John";
$age 25;
$is_active true;
?>
 

Data Types

PHP supports several data types, including:

Strings: Text values, e.g., "Hello, World!"
Integers: Whole numbers, e.g., 100
Booleans: Logical true or false, e.g., true or false
Arrays: Collections of data, e.g., ['apple', 'banana', 'orange']
Objects: Instances of classes in object-oriented programming.
NULL: Represents a variable with no value.

Operators

Operators in PHP allow you to perform operations on variables and values. Some common types of operators include:

Arithmetic operators: Used for math operations (+, -, *, /).
Assignment operators: Used to assign values to variables (=, +=, -=).
Comparison operators: Used to compare values (==, !=, >, <).
Logical operators: Used to combine conditions (&&, ||, !).

Control Structures

Control structures are used to dictate the flow of the program based on conditions. The most common control structures in PHP include:

If/Else Statements: Allows conditional execution.
<?php
if ($age 18) {
    echo 
"You are an adult.";
} else {
    echo 
"You are a minor.";

?>

Switch Statement: Used to execute one out of many blocks of code.
<?php
switch ($fruit) {
    case 
"apple":
        echo 
"You chose apple.";
        break;
    case 
"banana":
        echo 
"You chose banana.";
        break;
    default:
        echo 
"Invalid choice.";


Loops: Used to repeat a block of code multiple times.

For Loop: Repeats code a set number of times.
<?php
for ($i 0$i 5$i++) {
    echo 
$i;


While Loop: Repeats code as long as a condition is true.
<?php
while ($i 5) {
    echo 
$i;
    
$i++;
}
?>
 

Functions

Functions are reusable blocks of code that can be called with different inputs. PHP has many built-in functions, and you can also create your own. A simple user-defined function might look like this:


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

echo 
greet("Tom"); // Outputs: Hello, Tom</p> 
?>
 

Arrays

Arrays are used to store multiple values in a single variable. PHP supports both indexed and associative arrays. Indexed Arrays: Arrays with numeric keys.
<?php

$fruits 
= ["apple""banana""orange"];
echo 
$fruits[1]; 
// Outputs: banana Associative Arrays: Arrays with named keys.
<?php
$person 
= ["name" => "John""age" => 30];
echo 
$person["name"];  
// Outputs: John

Superglobals

PHP provides several built-in arrays that are globally accessible, called superglobals. Some of the most important ones include:

$_GET: Used to collect data sent via URL parameters.
$_POST: Used to collect data from form submissions.
$_SESSION: Used to manage session data across multiple pages.
$_COOKIE: Used to manage cookies.
Example: php Копирај кȏд // Assuming a URL like: example.com/?name=John echo $_GET['name']; // Outputs: John

Form Handling

One of PHP’s strengths is its ability to process data from HTML forms. Data from a form can be sent to a PHP script using either the GET or POST methods.

<form method="POST" action="process.php">
    <input type="text" name="username">
    <input type="submit" value="Submit">
</form>
 
The submitted data can then be accessed in process.php using $_POST['username'].

Error Handling

PHP provides mechanisms for handling errors, ensuring that your code doesn't break unexpectedly. You can use try-catch blocks to handle exceptions gracefully. Example:

<?php
try {
    
$file fopen("nonexistentfile.txt""r");
} catch (
Exception $e) {
    echo 
"Error: " $e->getMessage();
}
?>
 

PHP and MySQL

One of PHP's strengths is its ability to interact with databases like MySQL. Using PHP, you can connect to a MySQL database, retrieve, insert, update, or delete data. This makes PHP a powerful tool for building dynamic web applications that rely on user input or stored data. Example:
<?php
$servername 
"localhost";
$username "root";
$password "";
$dbname "my_database";

$conn = new mysqli($servername$username$password$dbname);

if (
$conn->connect_error) {
    die(
"Connection failed: " $conn->connect_error);
}

$sql "SELECT * FROM users";
$result $conn->query($sql);

if (
$result->num_rows 0) {
    while(
$row $result->fetch_assoc()) {
        echo 
"User: " $row["username"] . "<br>";
    }
} else {
    echo 
"No users found";
}
$conn->close();
?>
 







Privacy Policy