Category Archives: Web Page

A website is a document or electronic information capable of containing text, sound, video, programs, links, images, etc.

Adapted for the so called World Wide Web (WWW) and that can be accessed through a web browser

Control structures in PHP

Control structures in PHP

For control structures, PHP has the control sentences typical of high level languages

Variable statement

Variables in PHP are not assigned a predefined type

In PHP the type of variables depends on the value they contain at all times

Therefore it performs an automatic conversion of types

PHP recognizes the following types of values:

  • Numbers

    integers and real

  • Boolean values

    true and false

  • Strings
  • Arrays

    data type that associates values with keys (such as an ordered map)

  • Iterables

    pseudotype introduced in PHP 7.1

    Accepts any array or object that implements the interface Traversable

  • Resources

    reference to an external resource

  • The value null
  • Objects

    Created by the programmer or pre-defined by the language

Since there are no types of a priori variables, we do not have to specify the type of variable when declaring it

The variable declaration is made by prepending the reserved word $ to the variable name

It is possible to assign the value when we declare

The if sentence

The if sentence has the form:

The parentheses associated that define the condition are not optional

If the condition is true, instruction 1 will be executed; otherwise it is executed if there is instructution 2

The use of the sentence else is optional, so brackets have been used in the definition

If omitted, the instruction block will only be considered when the condition is true

A block of instructions is a set of instructions bounded by curly brackets

Keys after sentencing if are not required

If omitted and the condition was true, the following instruction will be executed

Otherwise, the subsequent instruction will be executed, independent of the condition state

Thus, the omission of keys after the sentence if it will allow us to write everything on a single line finished in ;

The elseif sentence

We can also use sentences if anities by sentencing elseif

Sentences elseif work just like a sentence if

But they will only be executed in case the condition of the sentence if was false

The switch sentence

Makes is select a group of sentence among several possible

It is an alternative to the use of sentences elseif anities

Its syntax is:

The expression in parentheses of the switch must be integer or string

Your result will be compared with the different values of the case

If it matches one of them, the following sentence will be moved to the case with that value and consecutive instructions will continue to be executed until a sentence is found break or reach the switch lock keys

In case the result of the expression does not match any value, execution will be passed to the next statement sentence on the label default, if there were, and it will continue as a case

The values in the case can be a constant expression

There can be two case with the same value

Unlike other languages, the sentence continue applies to switch and acts in a similar way to break

If you have a switch within a loop and want to continue to the next iteration of the outer cycle, it will be used continue 2

You can use a semicolon instead of a colon after a case

Consecutive instructions will continue to be executed normally until a sentence is found break or reach the switch lock keys

The match statement

It was added in PHP 8.0 version

Makes is select a group of sentence among several possible

It is an alternative to the use of sentences elseif nested and is similar to the statement switch

Similar to a sentence switch, a match expression has a subject expression that is compared against multiple alternatives

Unlike switch, will be evaluated at a value very similar to that of ternary expressions

But using an identity check (===) instead of a weak equality check (==)

Return a value

Subsequent values ​​are no longer processed, as is done in statements switch

It is not possible to execute blocks of code in each condition, as is done in statements switch

The expression used in the match must be complete, if it is not handled by any case the exception will be thrown UnhandledMatchError

Within the same case it can contain several expressions separated by a comma, it is similar to a OR logical

A special case is the pattern default, which allows matching anything that has not been previously matched

If several default patterns are used, the exception will be thrown E_FATAL_ERROR

Its syntax is:

Let's see how the example about beers that we saw with would look switch, now with match:

The while sentence

The while sentence has the form

The parentheses are not optional

If the condition is met, the sentence or instruction block is executed and the process is repeated until the condition is no longer met

The do sentence

The do sentence has the form

It's very similar to the sentence while, except that the condition goes after the instruction or block of instructions

So they are executed at least once even if the condition is false

The for sentence

In the case of such a sentece, in PHP we can distinguish two variants:

  • The loop for "classic"
  • The foreach loop

The loop for "classic"

This loop has a syntax very similar to that of C / C+

In this syntax:

Initialization creates the counter variable and gives it an initial value

Condition must be fulfilled for the loop to run

Depends on the variable index

Expression updates the value of the variable index

The equivalent of this while expression is:

The foreach loop

This loop has a syntax very similar to the for-each Java

Itera una variable $var sobre todas las propiedades de un objeto $obj que se le pasa

Así para cada valor de $var se ejecutaran las sentencias del bucle

Therefore, the loop will have as many iterations as the object's properties, and in each iteration the variable will have the value of the corresponding object's property with that iteration

Its syntax is:

The break sentence

The break sentence can be placed within a loop or anities loops

When you execute the break sentence exits the loop more internal

To all effects, the break sentence acts as a jump to the sentence following the loop in which it runs

The continue sentence

The continue sentence does not leave the loop but causes the next iteration to run

In the loop while the execution of the continue causes the program flow to jump to the condition

In the for loop the continue execution causes the increment expression to run, and then continue normally with the condition

That is, running the continue prevents the rest of the loop body from running

If you have a switch within a loop and you want to continue to the next iteration of the outer cycle, it will be used continue 2

Functions in PHP

Functions in PHP

To define functions we have the instruction function

After this reserved word is placed the name of the function followed by a list of arguments delimited by parentheses and separated by commas

Arguments

The argument step is optional and in some cases there may be functions that lack them

For example, the function phpinfo has no arguments

This function shows us information regarding the PHP module we are using and always returns the integer value 1

Type of arguments

Starting with PHP 7 you can optionally declare the type of arguments passed to the function

Supports types string, int, float, array, callable and clases

If the function user misinculated them or uses another type of data, PHP will return an error message indicating it

Default value arguments

Sometimes we need an argument to have a value, to avoid an error, even if the function user does not enter it

Note that default arguments become optional and that all arguments to the left of the first default value are required

Arguments by value or by reference

When we pass a value to a function, even if we modify it, when we exit the function it will retain its original value

This is the default situation and is called a argument by value

Since an in memory copy of the variable is used and when the function is exited, that copy of the variable is destroyed

In the event that we want changes made to the value of the variable to be preserved after exiting the function, we must use the symbol & in front of the variable name

This situation is called a argument by reference

Since a reference to the variable is used in memory, working directly on the variable and when the function is exited, all changes remain

Until PHP 5.0.5 it was possible to indicate that a function was by reference using the symbol & in front of the function name

However, as of PHP 5.3.0 it would go on to indicate with a message call-time pass-by-reference that its use was obsolete

As of PHP 5.4.0 it was completely removed and currently produces a fatal error

That is, only the symbol can be used & when passing arguments, never in the function name

We can only pass by reference:

  • Variables
  • References returned from functions

The return statement

The statement return it is the one that allows you to return the result of a function

Starting with PHP 7, you can optionally declare the type returned by the function

Supports types string, int, float, array, callable and clases

To declare the type, the symbol will be written : after the parentheses that follow the arguments and before the start key {

Functions are predefined by the language

Display functions

Echo

The function echo is used to send the output of its arguments to the browser

We have continuously used it in previous examples

It has the format:

It has the following characteristics:

  • We can do without the parentheses in their use, since they are optional

  • Converts all information to string before sending it to the browser

  • If we use several echo in a row, we will find that the result concatenates it in the same line

    To solve it we will have to use the HTML tag <br/>
    to jump the line

  • If we use several in a row, we will find that the result does not add a space at the end and therefore the content could show incomprehensible texts, lacking that space

    To solve it we will have to add a space at the end of the first echo or at the beginning of the next echo

printf

The function printf serves to send the output of your arguments to the browser in a format

It has the format:

To format a text you have to enter the following formatting characters preceded by the symbol %:

Format characters for text
Character Description
%

Literal percentage character

Does not require an argument

b

The argument is treated as a value of type integer and presented as a binary number

c

The argument is treated as a value of type integer and presented as the character with that ASCII value

d

The argument is treated as an integer type value and presented as a decimal (signed) number

e

The argument is treated with scientific notation (for example 1.2e+2)

The precision specifier indicates the number of digits after the decimal point as of PHP 5.2.1.

In previous versions, it was taken as the number of significant digits (minus one)

E

Like %e but it uses the capital letter (for example 1.2E+2)

f

The argument is treated as a float type value and presented as a floating point number (considering locale)

F

The argument is treated as a float type value and presented as a floating point number (regardless of locale)

Available since PHP 4.3.10 and PHP 5.0.3.

g

Like %e and %f

G

Like que %E and %f

o

The argument is treated as a value of type integer and presented as an octal number

s

The argument is treated and presented as a string

u

The argument is treated as an integer type value and presented as an unsigned decimal number

x

The argument is treated as a value of type integer and presented as a hexadecimal number (with lowercase letters)

X

The argument is treated as a value of type integer and presented as a hexadecimal number (with capital letters)

sprintf

The function sprintf serves to assign to its arguments, in a formatted way, the return variable

It has the same format as printf and supports the same formats

print_r

The function print_r serves to send the output of their arguments to the browser, displaying understandable information by people about the arguments

It's useful to be able to debug our code

It has the following format:

We can use it to see the full contents of an array

Functions for strings

Let's look at some of the most everyday functions for strings

If you need more, the full list can be found in the PHP manual

Uppercase and lowercase

The function strtoupper returns a copy of the string in uppercase

The function strtolower returns a lowercase copy of the string

Extract String

The function substr serves to extract a substring from the string we pass it as an argument

It has the following format:

Where $start is the starting position of the substring and $length the length that the substring will have

It can be useful when we need to extract a word from a text and we know in advance its position and length

Keep in mind that the position $start should start at 0

String length

The function strlen is used to count the length of the string

It has the following format:

Resuming the string from the example above

Position of a character in the String

The function strpos serves to find the position of a particular character in the string

It has the following format:

Where we find the needle ($needle, is the character to look for) in the haystack ($haystack, is the string we're looking for) and $offset, which is optional, is the starting number you start looking for

Keep in mind that the starting position starts at zero

Unless we specify the value of $offset

Find a text

The function strstr serves to find the first occurrence of a string

It has the following format:

It is very similar to substr, but it saves us having to use strpos intermediate

Array functions

Let's see some of the functions for arrays of daily use

If you need more, the full list can be found in the PHP manual

Count the number of items

The function count serves to count the total number of elements

It has the following format:

Optionally we can use the argument $mode which by default uses the value COUNT_NORMAL (counts elements sequentially) and for multidimensional arrays COUNT_RECURSIVE (count the elements recursively, that is, it goes through all the multidimensional arrays and adds the total number of elements)

Find a value in the array

Check if a value exists

The function in_array is used to check if a value exists inside an array

It has the following format:

Where we find the needle ($needle, is the character to look for) in the haystack ($haystack, is the string we're looking for) and $strict, which is optional, if is TRUE will check the types of $needle in $haystack

If $needle is a string, the comparison is made considering the case

Finding the first value

The function array_search serves to find the first value, if exists, within an array

It has the following format:

Where we find the needle ($needle, is the character to look for) in the haystack ($haystack, is the string we're looking for) and $strict, which is optional, if is TRUE will check the types of $needle in $haystack

If $needle is a string, the comparison is made considering the case

You have to be careful with the values returned by this function because it can return the Boolean value FALSE, but you can also return a non Boolean value that evaluates to FALSE

In versions prior to PHP 4.2.0 returned NULL in the event of a failure, rather than FALSE

Starting with PHP 5.3.0 returns NULL if you pass invalid parameters

Date formats

PHP doesn't have a date type

To work with dates use strings formatted with UNIX style timestamps

These timestamps are an integer value measured in seconds that begin to count from January 1, 1970

Timestamps

To get the current timestamp we can use the function time which has the following format:

The obtained value is easy to manipulate, as we can add multiples to it:

  • 3600 to add hours
  • 86400 to add days
  • 604800 to add weeks

Formatted string

We can also use a format string to work with dates using the function date which has the following format:

Where $format is the string with the format we want to use, $timestamp, which is optional and by default takes the function time, is a UNIX timestamp

To format a date you have to enter the following formatting characters:

Date formatting characters
Character Description
d

Day of the month, 2 digits with leading zeros

D

String for the day, three letters

j

Day of the month without leading zeros

l (lowercase L)

String for the day of the week

N

Numerical representation ISO-8601 of the day of the week

Added in PHP 5.1.0.

S

Ordinal suffix for the day of the month, 2 characters

w

Numerical representation of the day of the week

z

The day of the year (starting with 0)

W

Week number of the year ISO-8601, weeks start on Monday

F

A full textual representation of a month, such as January or March

m

Numerical representation of a month, with leading zeros

M

A short textual representation of one month, three letters

n

Numerical representation of a month, without leading zeros

t

Number of days of the given month

L

If it is a leap year

o

Year according to the week number ISO-8601

This has the same value as Y, except that if the week number belongs to the previous or next year, that year is used instead

Added in PHP 5.1.0.

Y

A complete numerical representation of a year, 4 digits

y

A two digit representation of a year

a

lowercase am or pm

A

uppercase am or pm

B

Internet time

g

12 hour one hour format with no leading zeros

G

24 hour one hour format with no leading zeros

h

12 hour one hour format with leading zeros

H

24 hour one hour format with leading zeros

i

Minutes with leading zeros

s

Seconds with leading zeros

u

Microseconds

Added in PHP 5.2.2.

date() will always generate 000000 when taking a parameter of type integer, while DateTime::format() supports microseconds if DateTime was created with microseconds

v

Milliseconds

Added in PHP 7.0.0.

The same observation as for u

e

Time zone identifier

Added in PHP 5.1.0.

I (capital i)

The date is in summer time or not

O

Greenwich Mean Time (GMT) difference in hours

P

Difference from Greenwich Mean Time (GMT) with two points between hours and minutes

Added in PHP 5.1.3.

T

Time zone abbreviation

Z

Time zone index in seconds

The index for time zones west of UTC is always negative, and for those east of UTC it is always positive

c

Date ISO 8601

Added in PHP 5

r

Date in the format RFC 2822

U

Seconds in UNIX format (January 1, 1970 00:00:00 GMT)

Get a date from a string

Using a delimiter

From a string we can pick up a date using the function explode which has the following format:

Where $delimiter is the character used to delimit the values, $string the string that contains the date we want to manipulate and $limit an optional value whose default value is 1, which indicates the maximum number of return values

If $limit negative will return all values by removing the value of $limit from the end

And if it's 0 it's going to be treated like 1

And then we'll use the function mktime to create the UNIX type timestamp, which has the following format:

Where $hour is the hour, $minute is the minutes, $second, the seconds, $month is the month, $day is the day $year is the year and $is_dst is summer time or not (-1 if is not)

All parameters are optional, in case you don't enter any, the result of the function will be taken time

Starting with 5.1, when the call is made without arguments, it issues a warning of type E_STRICT: use function time() in its place

Converting a string to date format

From a string we can pick up a date using the function strtotime which has the following format:

Where $time is the string from which we want to get the date, $now, which is optional and by default takes the function time, is a UNIX timestamp

Starting with PHP 5.0.0, microseconds started to be allowed, but were ignored

In PHP 5 up to 5.0.2, now and other relative moments are wrongly computed like today's midnight

This differs between versions where it is computed as the current moment

As of PHP 5.1.0 it shows the error E_STRICT and E_NOTICE when errors occur with time zones

And returns FALSE if fails, instead of -1

In PHP 5 through 5.2.7, requests for an occurrence of a given day of the week in a month where that day of the week was the first day of the month, incorrectly added a week to the returned timestamp

This was fixed in 5.2.7 and is maintained in later versions

Before PHP 5.3.0, 24:00 was not a valid format and returned FALSE

The relative time formats that were supplied to the parameter $time such as this week, previous week, last week, and next week were interpreted as a period of 7 days relative to the current date and time, rather than a period of the week from Monday to Sunday