Abrir tópico con la navegación







do while


















An Array in the PHP is currently a commanded map. A map is a type that relates values with keys. You can use it as an array, or a list (vector), hashtable, dictionary, collection, stack, line and probably more. As you can have another Array PHP as a value, you can easily simulate trees.The explanation of these structures is beyond the target of this manual.


An Array can be created with the constructor of Array () language.

array( [chave =>] value
, ...
// key pode ser tanto string ou um integer
// value pode ser qualquer coisa

$arr = array("foo" => "bar", 12 => true);

echo $arr["foo"]; // bar
echo $arr[12]; // 1

The key can be integer or a string .

The value can be any type PHP:

$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));

echo $arr["somearray"][6]; // 5
echo $arr["somearray"][13]; // 9
echo $arr["somearray"]["a"]; // 42

If you to specify a key that already in use, then the value associated to it is updated.


array(5 => 43, 32, 56, "b" => 12);

// ... this array
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);


Creating/modifying with the square brakets syntax

That is another way to create and/or update an array as in the example below.


$arr[key] = valuer;
$arr[] = value;
//key can be integer or string

// value can be anything

To remove a pair key/value, you need to apply the unset().

$arr = array(5 => 1, 12 => 2);

$arr[] = 56; // The same as $arr[13] = 56;

$arr["x"] = 42; // new element to array with "x" key

unset($arr[5]); //remove an array element

unset($arr); // remove the complete array


It notices that the greater entire key, used for, this necessarily don’t need existing in the Array. It can have existed in the Array since the last time that the Array was indexed. He sees the following example

// Creating an array
$array = array(1, 2, 3, 4, 5);

// Removing the array values leaving an empty structure.
foreach ($array as $i => $value) {

// Adding an item
$array[] = 6;

// Reindexing
$array = array_values($array);
$array[] = 7;

The example above must produce the following exit:

[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[0] => 6
[1] => 7



$a = array( 'color' => 'red',
'flavor' => 'sweet',
'form' => 'round',
'name' => 'apple',
4// key 0

// or
$a['color'] = 'red';
$a['flavor'] = 'sweet';
$a['form'] = 'round';
$a['name'] ='apple';
$a[] = 4; // key 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// array( 0 => 'a' , 1 => 'b' , 2 => 'c' ),
// or array('a', 'b', 'c')



Break cancels the execution of commands like foreach while, do. .while or switch current.

Break accepts an optional numerical argument.

$arr = array ('um', 'dois', 'três', 'quatro', 'STOP', 'cinco');
while (list (, $val) = each ($arr)) {
if ($val == 'STOP') {
echo "$val<br>\n";

$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "No 5<br>\n";
break 1;
case 10:
echo "N# 10;<br>\n";
break 2;


Continue is used inside of loops structures to jump out the current Loop remaining portion of the iteration and to continue the execution at the beginning of the next iteration.

while (list ($key, $value) = each ($arr)) {
if (!($key % 2)) {
do_something_odd ($value);

$i = 0;
while ($i++ < 5) {
echo "Out<br>\n";
while (1) {
echo "&nbsp;&nbsp;Middle<br>\n";
while (1) {
echo "&nbsp;&nbsp;Inside<br>\n";
continue 3;
echo "It will never be displayed.<br>\n";
echo "Neither this<br>\n";


(PHP 3, PHP 4 )

date - Format the date and local hour.


string date ( string format [, int timestamp])

String in accordance with returns one the format from string using the given whole number timestamp or to the local current hour if no teamses tamp is given. In other words,timestamp is optional and the standard for the value of time.

Table1. The following characters are recognized in format to parameter string

format character


Exemples (return values)


Lowercase Ante meridiem and Post meridiem

am or pm


Uppercase Ante meridiem and Post meridiem

AM ou PM


Swatch Internet time

000 até 999


Dia do mês, 2 digitos com leading zeros

01 to 31


Text representing day, with 3 letters

Mon through Sun


Text representing month

January through December


12-hour format no leading zeros

1 a 12


24-hour format no leading zeros

0 a 23


12-hour format with leading zeros

01 a 12


24-hour format with leading zeros

00 a 23


Minutes with leading zeros

00 para 59


summer time

1 summer time, 0 no summer time


Day no leading zeros

1 to 31


Text representing week days

Sunday through Saturday


leep year

1 leep year, 0 not leep year


Month (numeric) with leading zeros

01 a 12


Text representing month in short (3 letters)

Jan a Dec


Month (numeric) no leading zeros

1 a 12


Diferença ao horário de Greenwich (GMT) em horas

Exemplo: +0200


RFC 822 formatted date

Exemplo: Thu, 21 Dec 2000 16:01:07 +0200


Seconds with leading zeros

00 a 59


Sufixo ordinal inglês para o dia do mês, 2 caracteres

st, nd, rd ou th. Funciona bem com j


Days in a month

28 a 31


Timezone setting

Examples: EST, MDT ...


Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

See also time()


week day numeric

0 (para Domingo) a 6 (para Sábado)


Número da semana do ano ISO-8601, semanas começadas na segunda-feira (adicionado no PHP 4.1.0)

Exemplo: 42 (a 42nd (quadragésima segunda) semana do ano)


Year with 4 digits

Examples: 1999 ou 2003


Year with 2 digits

Examples: 99 ou 03


Day in a year

0 a 366


Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.

-43200 até 43200


Example 1. date() examples

// Prints something like: Wednesdayecho date("l");// Prints something like: Wednesday 15th of January 2003 05:51:38 AMecho date ("l dS of F Y h:i:s A");// Prints: July 1, 2000 is on a Saturdayecho "July 1, 2000 is on a " . date ("l", mktime(0,0,0,7,1,2000));?>


// Assuming today is: March 10th, 2001, 5:16:18 pm$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm$today = date("m.d.y");                         // 03.10.01$today = date("j, n, Y");                       // 10, 3, 2001$today = date("Ymd");                           // 20010310$today = date('h-i-s, j-m-y, it is w Day z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.$today = date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month$today = date("H:i:s");                         // 17:16:17?>


Loops do. .while is similar to loop, except for the fact of that the condition is verified in the end of each iteration instead of in the start. The main difference of loops while regular is that the first iteration of a Loop of .while guaranteeing is executed (the condition alone is verified in the end of the iteration) whereas it can necessarily not twirl in a normal Loop while (the condition is verified in the start of each iteration, if it is evaluated as FALSE soon in the start, the execution of the Loop would finish immediately).

It has only syntax for loops of while:

$i = 0;do {print $i;} while ($i > 0);?>

Loop above would twirl accurately one time, since that after the first iteration, when the condition is verified, it is evaluated as it FALSE isn’t greater who zero 0) and the execution of the Loop finishes.

Advanced users of C can be made familiar to the differentiated use of the Loop of .while, allowing to the end of the execution in the way them code blocks, generalizing them with it .while (0), and using the instruction break. I break up it of code following demonstrates this:

do {if ($i < 5) {print "i não é grande o suficiente";break;}$i *= $factor;if ($i < $minimum_limit) {break;}print "i está Ok";/* process i */} while(0);?>

If it doesn’t worry if you it did not understand this of the certain form no way or. You can codify simple or exactly powerful scripts without using this “resource”.



Frequently you go to want executing an instruction if a certain condition will be found and a different instruction if the condition will not be found. That is what else makes. Else extends to a command if to execute an instruction case the expression in the command if either evaluated as it FALSE. For example, the code to follow would show it is greater that b if $a will be greater that $b and it isn’t greater that b contrary case:

if ($a > $b) {print "a é maior que b";} else {print "a NÃO é maior que b";}?>
The command else is only executed if the expression if will be evaluated as FALSE, and if having any expression elseif, if all they will only be evaluated as it also FALSE (it sees elseif).


elseif, as its name suggests, is a combination of if and else. In the same way that else, it extends to a command if executing a different instruction in the case of the original expression if to be evaluated as FALSE. However, in contrast to else, it will only execute that alternative expression if the conditional expression of elseif will be evaluated as TRUE. For example, the code following would show it is greater that b, a it is equal the b or it she is minor who b:

if ($a > $b) {print "a é maior que b";} elseif ($a == $b) {print "a é igual a b";} else {print "a é menor que b b";}?>

If can have several inside of the same instruction. The first expression elseif(it will be had) that it will be evaluated as TRUE will be executed. In the PHP, you also it can write “else if” (in two words) and the behavior will be identical to one 'elseif' (in one alone word). The meaning syntactic is slightly different (if you are made familiar to C, them you have behavior the same), but in the end of accounts both would have the same behavior accurately.

The command is only executed if the preceding expression if and any previous expressions elseif will be evaluated as FALSE, and the current expression elseif will be evaluated as TRUE.


Loops will be is the bows most complex in PHP. They behave as its compatible in C. syntax of a Loop will be is:

for (expr1; expr2; expr3) instrucoes

The first expression (expr1) is evaluated (executed) a time unconditionally in the start of the Loop.

In the start of each iteration, expr2 is evaluated. If it is evaluated as TRUE, the Loop continue and (s) the command (s) nestled (s) (they are) is executed (s). If she is evaluated as SHE FALSE, the execution of the 'Loop' finishes.

In the end of each iteration,expr3is evaluated (executed).

Each one of the expressions can be empty.expr2> empty means that the Loop can twirl indefinitely (PHP considers it implicitly as TRUE, as in C). This can’t be so useless how much you can think, therefore frequently you can want to finish the 'Loop' using a break conditional instruction instead of using the expression-truth of it you will be.

It considers the following examples. All they show to numbers of 1 the 10:

/* exemplo 1 */for ($i = 1; $i <= 10; $i++) {print $i;}/* exemplo 2 */for ($i = 1; ; $i++) {if ($i > 10) {break;}print $i;}/* exemplo 3 */$i = 1;for (;;) {if ($i > 10) {break;}print $i;$i++;}/* exemplo 4 */for ($i = 1; $i <= 10; print $i, $i++);?>

The first example seems to be prettiest (or perhaps the room), but you can perceive that the possible use of empty expressions in bows will be if it becomes practical in some occasions.

The PHP also supports the alternative syntax of two-points bows will be:

for (expr1; expr2; expr3): instrucoes; ...; endfor;


The PHP4 (but not it PHP3) includes a constructor foreach, much similar to the Perl and other languages. This offers an easy way to iterar on matrices. foreach only functions with arrays, and will launch an error if to try to use it in an variable of any different type or in variable not initialized. It has two syntaxes; second it is an abbreviation, but useful, of the first one:

foreach (expressao_array as $valor) instrucoes
foreach (expressao_array as $chave => $valor) instrucoes

The first form sweeps one given first one given for expression_array. In each Loop, the value of the current element is attributed the $value and the internal hand of the matrix is advanced in a position (thus, in the next iteration you it will be looking at for the next element).

The second form makes the same thing, except for the fact of that the key of the current element will be attributed to the 0 variable $key in each iteration.

Note:When foreach initiates its first execution, the internal hand of the matrix is zeroed automatically for the first element of the Array. This means that you do not need to call reset() before a Loop foreach.
Note: It also notices that foreach operates on a copy of the specified Array, not it proper Array, and therefore, the hand of the original Array is not modified as in the instruction each(), that it modifies the element of the selected Array, but this doesn’t reflect the original Array. However, the internal hand of the original Array is put into motion by the processing of the Array. Assuming that the bow foreach twirls until the end, the internal hand of the Array will be located in the end of the Array.
Note:foreach has the ability to prevent messages of error with “@”.

You can have noticed that following items is functionally identical:

$arr = array("one", "two", "three");reset ($arr);while (list(, $value) = each ($arr)) {echo "Valor: $value<br>\n";}foreach ($arr as $value) {echo "Valor: $value<br>\n";}?>

Os seguintes também são funcionalmente idênticos:

reset ($arr);while (list($key, $value) = each ($arr)) {echo "Chave: $key; Valor: $value<br>\n";}foreach ($arr as $key => $value) {echo "Chave: $key; Valor: $value<br>\n";}?>

More examples to demonstrate the uses:

Functions defined for the user

A function can be defined using it syntax as the following one:

Psuedo-código que de demonstração de uma função

function foo ($argumento_1, $argumento_2, ..., $argumento_n)
echo "Exemplo de função.\n";
return $valor_retornado;

Any valid code PHP can appear inside of a function, exactly other functions and definitions of classrooms.

When a function is defined conditionally as in the two examples below, its definition can be processed before being called.

Funções definidas condicionalmente


$makefoo = true;

/* Nos nao podemos chamar foo() daqui
porque ela ainda não existe,
mas nos podemos chamar bar() */


if ($makefoo) {
function foo ()
echo "Eu não existo até que o programa passe por aqui.\n";

/* Agora nos podemos chamar foo()
porque $makefoo foi avaliado como true */

if ($makefoo) foo();

function bar()
echo "Eu existo imediatamente desde o programa começar.\n";


Funções dentro de funções

function foo()
function bar()
echo "Eu não existo até foo() ser chamada.\n";

/* Nós não podemos chamar bar() ainda
porque ela ainda não foi definida. */


/* Agora nós podemos chamar bar(),
porque o processamento de foo()
tornou a primeira acessivel */



The PHP doesn’t support overload of functions, and also it isn’t possible to cancel or to modify the definition of functions previously declared.

Note: Names of functions are insensitive to the case, but it is better to call the functions in the same way that it appears in the declarations.


The construction if is the one of the most important implementations of many languages, including PHP.Allows the conditional execution of fragments of code. The PHP implements a structure if that it is similar to that one of the C: /P>

if (expressao)

As described in the section on expressions, expression is evaluated by its Boolean context. If expression will be evaluated as TRUE, the PHP will execute instructors, and it will have evaluated itself as FALSE, will be ignored. More information on the evaluation for FALSEcan be found in the section converting for Boolean.

The examples to follow would show that it is greater that b if $a will be greater that $b:

if ($a > $b)
print "a é maior que b";

Frequently you go to want having more than an instruction is executed conditionally. And is clearly, does not have necessity of generalize each instruction with a clause if. Instead of this, you can place some instructions in a grouping of commands. For example, this code would show it is greater that b if $a will be greater that $b, and then would attribute the value of $a for $b:

if ($a > $b) {
print "a é maior que b";
$b = $a;

Commands if can inside indefinitely be nestled of other commands if, what it makes with that you completes flexibility for the conditional execution of some parts of its program.


(PHP 3, PHP 4 )

ltrim -- It removes whitespace of the beginning of string


string ltrim ( string str [, string charlist])

Note: As the parameter was added in PHP 4.1.0

This function returns one string with whitespace removed from the beginning of str. Without as the parameter, ltrim() will remove these characters: