You are on page 1of 16

PHP Variables

<="" p="">

In PHP, a variable is declared using a $ sign followed by the variable name. Here, some imp
variables:

o As PHP is a loosely typed language, so we do not need to declare the data types of t
analyzes the values and makes conversions to its correct datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:

1. $variablename=value;

Rules for declaring PHP variable:

o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special
o PHP variables are case-sensitive, so $name and $NAME both are treated as different variab

PHP Variable: Declaring string, integer, and float


Let's see the example to store string, integer, and float values in PHP variables.

File: variable1.php

1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>

Output:

string is: hello string


integer is: 200
float is: 44.6

PHP Variable: Sum of two variables


File: variable2.php

1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>

Output:

11

PHP Variable: case sensitive


In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR

File: variable3.php

1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>

Output:

My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is
PHP Variable: Rules
PHP variables must start with letter or underscore only.

PHP variable can't be start with numbers and special symbols.

File: variablevalid.php

1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>

Output:

hello
hello

File: variableinvalid.php

1. <?php
2. $4c="hello";//number (invalid)
3. $*d="hello";//special symbol (invalid)
4.
5. echo "$4c <br/> $*d";
6. ?>

Output:

Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE
or '$' in C:\wamp\www\variableinvalid.php on line 2

PHP: Loosely typed language


PHP is a loosely typed language, it means PHP automatically converts the variable to its correct d

← PrevNext →
ADVERTISEMENT
ADVERTISEMENT

For Videos Join Our Youtube Channel: Join


Now

Feedback

o Send your Feedback to feedback@javatpoint.com

Help Others, Please Share

Learn Latest Tutorials

Splunk

SPSS

Swagger

Transact-SQL
Tumblr

ReactJS

Regex

Reinforcement Learning

R Programming

RxJS

React Native

Python Design Patterns

Python Pillow
Python Turtle

Keras

Preparation

Aptitude

Reasoning

Verbal Ability

Interview Questions

Company Questions

Trending Technologies
Artificial Intelligence

AWS

Selenium

Cloud Computing

Hadoop

ReactJS

Data Science

Angular 7

Blockchain
Git

Machine Learning

DevOps

ADVERTISEMENT

B.Tech / MCA

DBMS

Data Structures

DAA

Operating System

Computer Network
Compiler Design

Computer Organization

Discrete Mathematics

Ethical Hacking

Computer Graphics

Software Engineering

Web Technology

Cyber Security

Automata
C Programming

C++

Java

.Net

Python

Programs

Control System

Data Mining

Data Warehouse
ADVERTISEMENT

Type System ¶
PHP uses a nominal type system with a strong behavioral subtyping relation. The
subtyping relation is checked at compile time whereas the verification of types is
dynamically checked at run time.

PHP's type system supports various atomic types that can be composed together to
create more complex types. Some of these types can be written as type declarations.

Atomic types ¶

Some atomic types are built-in types which are tightly integrated with the language and
cannot be reproduced with user defined types.

The list of base types is:

o Built-in types

o null type

o Scalar types:

o bool type

o int type

o float type

o string type

o array type

o object type

o resource type

o never type

o void type

o Relative class types: self, parent, and static

o Value types
o false

o true

o User-defined types (generally referred to as class-types)

o Interfaces

o Classes

o Enumerations

o callable type

Composite types ¶

It is possible to combine multiple atomic types into composite types. PHP allows types
to be combined in the following ways:

o Intersection of class-types (interfaces and class names).

o Union of types.

Intersection types ¶

An intersection type accepts values which satisfies multiple class-type declarations,


rather than a single one. Individual types which form the intersection type are joined by
the & symbol. Therefore, an intersection type comprised of the types T, U, and V will be
written as T&U&V.

Union types ¶

A union type accepts values of multiple different types, rather than a single one.
Individual types which form the union type are joined by the | symbol. Therefore, a
union type comprised of the types T, U, and V will be written as T|U|V. If one of the
types is an intersection type, it needs to be bracketed with parenthesis for it to written
in DNF: T|(X&Y).

Type aliases ¶

PHP supports two type aliases: mixed and iterable which corresponds to the union
type of object|resource|array|string|float|int|bool|null and Traversable|
array respectively.

Nota: PHP does not support user-defined type aliases.


+add a note

User Contributed Notes


There are no user contributed notes for this page.
 Tipos
 Introducción
 Type System
 NULO
 Booleanos
 Números enteros (Integers)
 Números de punto flotante
 Cadenas de caracteres (Strings)
 Numeric strings
 Arrays
 Objetos
 Enumerations
 Recursos
 Llamadas de retorno (Callbacks / Callables)
 Mixed
 Void
 Never
 Relative class types
 Value types
 Iterables
 Declaraciones de tipo
 Manipulación de tipos

 Copyright © 2001-2024 The PHP Group

 My PHP.net

 Contact

 Other PHP.net sites

 Privacy policy

PHP (Hypertext Preprocessor) is a widely-used server-side scripting language


designed for web development. It is especially suited for creating dynamic web
pages and applications. PHP scripts are executed on the server, and the result is
sent to the client's web browser, which then renders the page.

Here are some key features and aspects of PHP:


1. Syntax: PHP syntax is similar to C and Perl, making it easy to learn for
those familiar with these languages. It is embedded within HTML code.
phpCopy code
<?php // PHP code goes here ?>
2. Server-Side Scripting: PHP is a server-side scripting language, meaning
that it runs on the web server, not on the client's browser. The server
processes the PHP code and sends the output (usually HTML) to the
client's browser.
3. Open Source: PHP is an open-source scripting language, which means
its source code is freely available and can be modified and redistributed.
4. Platform Independence: PHP is platform-independent, meaning it can
run on various operating systems, including Windows, Linux, macOS, and
others.
5. Database Integration: PHP has strong support for database integration,
and it is often used to interact with databases such as MySQL,
PostgreSQL, SQLite, and others.
6. Frameworks: There are several PHP frameworks, such as Laravel,
Symfony, CodeIgniter, and Zend, that provide a structured way to build
web applications, promoting code organization and reusability.
7. Community Support: PHP has a large and active community of
developers. There are numerous online resources, forums, and
documentation available for PHP development.
8. Security: PHP has built-in security features, and developers can follow
best practices to ensure the security of their applications. However, as
with any programming language, it's important for developers to be
aware of common security pitfalls.

Here's a simple example of a PHP script that outputs "Hello, World!":

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

This script uses the echo statement to output the string "Hello, World!" to the
browser.

Remember that PHP is often used in conjunction with HTML to create dynamic
and interactive web pages. It is a versatile language with a long history in web
development.
TIC 2º BTO IES Grande Covián Curso 2017-18 Zaragoza 1 de 33 1. Introducció n a PHP Páginas
PHP Una página PHP es una página web normal en la que utilizamos la extensión “.php” en
lugar de “.htm” o “.html”. En una página “.php” se pueden insertar bloques de código escrito
en lenguaje PHP. Estos bloques de código reciben el nombre de scripts. Script PHP: Bloque de
código escrito en lenguaje PHP dentro de una página web. Un script PHP se limita
anteponiendo los símbolos . El siguiente script ejecuta la función phpinfo(). Esta función
muestra información sobre la versión y configuración de la versión de PHP instalada en el
servidor. Dentro de una misma página PHP puede haber tantos scripts como se desee. Es muy
recomendable indentar el código (no es necesario) para mejorar su legibilidad. Sitios web
dinámicos con PHP Los sitios web tradicionales son sitios web estáticos. Esto quiere decir que
muestran información permanente. En ellos el navegante se limita a obtener dicha
información, sin poder interactuar con la página web visitada. En esquema: 1. El navegador la
solicita la página web al servidor web correspondiente. 2. El servidor busca y lee el fichero que
corresponde a esa página web 3. El servidor envía el fichero al navegador y este muestra la
página web al usuario. En un sitio web dinámico los ficheros que muestra el navegador no son
archivos estáticos guardados en el disco, sino que las páginas se generan automáticamente en
el servidor adaptándose a los datos que hayamos envidado en la petición del navegador. PHP
permite la creación de sitios web dinámicos. En esquema: TIC 2º BTO IES Grande Covián Curso
2017-18 Zaragoza 2 de 33 1. El usuario escribe la dirección de la página web en su navegador y
este la solicita al servidor web correspondiente. 2. El servidor detecta que dentro de la página
hay uno o varios programas PHP y los envía al intérprete del lenguaje. 3. El intérprete del
lenguaje completa la ejecución del programa PHP. 4. El resultado final del programa se envía al
servidor 5. El servidor envía el fichero al navegador que muestra la página web al usuario 2.
Funciones básicas Escribir por pantalla, echo Aunque existen otras opciones utilizaremos la
función echo con la forma: echo “texto”; - Escribe el texto entre comillas. - Como toda orden
termina con punto y coma. - Hay dos tipos de comillas (“) y (‘), se puede utilizar cualquiera de
los dos. Si van anidadas (queremos que aparezca un texto entre comillas) se van alternando. -
Para encadenar varios “texto” se separan por comas o por puntos.
actúa como retorno de carro. Comentarios De una sola línea Se coloca // al comienzo de la
línea o tras el punto y coma. De varias líneas Se coloca /* al comienzo de la primera línea y */
al final de la última. Estos no se pueden anidar. En la parte HTML Constantes Se pueden usar
tal cual o utilizar la función define para asignarle un nombre: define(“nombre”,”valor”) - Si
valor es numérico no es preciso colocarlo entre comillas. - Al realizar operación aritmética con
una constante cuyo valor comienza con cifras y continúa con letras se toma como valor el de
las cifras hasta la primera letra. - Se puede definir valor como el resultado de una operación
aritmética. - OJO: Distingue mayúsculas de minúsculas. TIC 2º BTO IES Grande Covián Curso
2017-18 Zaragoza 3 de 33 Constantes predefinidas: - No requieren la orden define. Algunos
ejemplos son: - __FILE__ Nombre del fichero ejecutado y ruta en el servidor. - __LINE__ Nº
línea en el fichero cuyo script se está interpretando. - PHP_OS Sist Operativo del servidor. -
PHP_VERSION Variables Para definir su valor se utilizará una expresión del tipo: $variable =
valor; - El nombre ha de comenzar con $ seguido de una letra. - Se distingue
Mayúsculas/Minúsculas. - No es necesario definir el tipo. - Si valor es un texto, ha de ir entre
comillas. - Nos podemos referir a su valor desde cualquier parte del script, salvo que sea una
variable definida en una función. En ese caso sólo tiene sentido en el interior de la función. -
Una variable definida en una función no puede utilizarse en el script (toma valor cero o “”). -
Variable global: EXCEPCION a lo anterior. La función puede utilizar valores de variables
externas si se ha incluido en la función la orden “global nombrevariable;”, se busca el valor de
la variable en el resto del script). - Existe otro tipo Variable Superglobal, se puede acceder a su
valor desde cualquier punto sin utilizar la orden global. - Variables estáticas. Si definimos una
variable como estática dentro de una función, cuando salimos de su ámbito conserva el valor
que tenga en el momento de salir y la línea que le da valor inicial la primera vez que se ejecuta
no volverá actuar cuando se ejecute la función hasta que actualicemos la página. Para definir la
variable $a como estática y con un valor inicial utilizaremos la orden (static $a = 3;), al salir de
la función $a conservará el último valor que se haya asignado hasta que se actualice la página.
Tipos de variables En PHP no es necesario definir el tipo. Según sea el valor almacenado se
adapta el tipo. Hay tres tipos Integer: Enteros (+/- 231) Double: Coma flotante String:
Cadenas - gettype(variable); Devuelve una cadena de caracteres (Integer, double o string)
según cual sea el tipo de la variable. - Forzar tipo en una variable y asignarle a la vez valor: o
$a=((integer)4.5); fuerza y convierte a tipo entero (trunca). o $a=((int)45); fuerza tipo entero. o
$a=((double)45); fuerza tipo double. o $a=((float)45); fuerza tipo double. o $a=((real)45);
fuerza tipo double. o $a=((string)4.5); fuerza y convierte a tipo string. - Forzar tipos en una
variable ya definida: o Settype(var,tipo) tipo ha de ir entre comillas.

You might also like