Category Archives: Programming

Programming is the process of designing, coding, debugging and maintaining the source code of programs

Events

Events

The actions that the user performs or the changes you make in the page are known under the name of events

An event is the sign that 'something' has happened

Syntax of events

You need to specify a selector, to know which element the event will interact with, followed by the event in parentheses

We will use the following sample HTML, that contains a simple form, to get to know the use of the events, accompanied by a file that we will call event.js

To process the form, we have also added a file form.php however, we are not going to use the examples on events

Item events

This type of event is that normally used by the user to interact with the elements of the HTML, when you hover the mouse over the element or is pressed, among others

Among the most important of which we highlight:

  • focus

    is triggered when the focus goes to the element

  • blur

    is triggered when the focus goes to another element or lose it

  • click

    is activated when you click on the element

  • dblclick

    is activated when you double click on the element

In the example we have selected the element with the id button, and responds to the click event that has as a parameter the variable warning

It could have included the code inside the click event, but wanted to emphasize that the parameters can be a variable that contains a function, so we can have different variables with different behavior, without having to modify our code

Mouse events

Occur when the user uses the mouse within the HTML document or any of the elements that compose it

Among the most important of which we highlight:

  • mousedown

    turns on when you press a mouse button

  • mouseup

    is activated when you stop pressing a mouse button

  • mousemove

    is triggered when the mouse moves

  • mouseover

    is triggered when the mouse moves over an item (when we enter in the item)

  • mouseout

    is triggered when the mouse leaves the element (when we leave the element)

In the example, we have added a couple of events that change the type of letter when you pass the mouse over the element with id button

It is possible to assign to these event parameters that contain information about a mouse event

Among the most important of which we highlight:

  • screenX and screenY

    represent the coordinates of the mouse pointer with respect to the global coordinates of the screen

  • clientX and clientY

    represent the coordinates of the mouse pointer with respect to the browser window

  • button

    is the number of the button that has been pressed (left = 0, center = 1, right = 2)

    If you do not want to pass it as a parameter, we can use the property buttonsthat includes more buttons, as the mouse wheel or the forward and back buttons of the browser

In the example we have modified the variable warning to detect which button has been clicked and what position you had the mouse on the screen, when it has been clicked

Keyboard events

Occur when the user uses the keyboard

Among the most important of which we highlight:

  • keydown

    turns on when you press a key

  • keyup

    is activated when you stop pressing a key

  • keypress

    is activated when you press and stops the press of a key

It is possible to assign to these event parameters that contain information about the event from the keyboard

Among the most important of which we highlight:

  • char or charCode

    is a string with the character that has been pressed (provided that the same is representable)

  • key or keyCode

    it is an identifier that represents the key that has been pressed

    You can see the complete list on the page for developers Mozilla

  • ctrlKey,, shitKey and altKey

    these are fields that indicate whether the key Control, Shift or Alt key had been pressed when the event occurred keyboard

In the example has been added to the variable key with parameters to capture the keystrokes when you type in the element with the id login, and has modified the set of calls to use, using the keypress event

Touch events

These events are produced by touching a touch screen

Are similar to those produced by a mouse, but its delay is much lower

Because of this, conflicts can occur with mouse events, this is why it is advisable to disable them, not to run similar events twice

Among the most important of which we highlight:

  • touchstart

    is activated when the finger touches the surface of the screen

  • touchend

    is activated when the finger stops pressing the surface of the screen

  • touchmove events

    is activated when the finger slides on the surface of the screen

  • touchenter

    is activated when the finger is moved over an item (when we enter in the item)

  • touchleave

    is triggered when the finger leaves the element (when we leave the element)

  • touchcancel

    is activated when the finger goes outside the bounds of the browser window

Form events

The forms have their own events, among the most important of which we highlight:

  • click

    it is activated when we click the mouse on an item
    It is usually used with buttons (button, submit)

  • change

    is triggered when the user modifies the value of a text element

    This is normally used with input of type text, textarea or drop-down lists to select an option

  • focus

    is activated when the user selects a form element

  • blur

    is triggered when the user moves to another form element

  • submit

    is activated when the user performs the action of submitting the form (not just when pressed the button submit, which can be simulated at the push of a button which makes the time of submit or when you force a call to the event from another event)

    In addition, the submit event generates the events mousedown, click, mouseup and submitin that same order, which allows us to perform validations on the form elements before final submission

  • reset

    is activated when the user performs the action of resetting the form (not only when you press the reset button, which can be simulated at the push of a button that makes the times of reset, or when force a call to the event from another event)

In the example, we have added the variables to send (to validate the fields login and pass) and write (to validate that it does not enter the @ symbol into the field, pass); has modified the set of calls to use, using the events submit and change

Modification of styles

Modification of styles

JQuery allows to modify easily the styles and the CSS properties of our web page

Add or remove CSS properties

By using the methods addClass() and removeClass() we can assign or remove a CSS class from any element

In the example, add the styles are important and color the element with id div01 when you press the button btn01, and eliminates the color style

Manipulation of CSS properties

The method css() allows us to view or modify any property of the stylesheet of an HTML element

It has the following syntax:

In case you only want to see the property, we will omit the parameter value and if we want to modify it, we'll use that parameter

In the example, we have used three paragraphs different with a style for the background color different, if you push the button with id btn03 we can see that with the css method, we have changed all the paragraphs to yellow

Effects

Effects

JQuery allows you to, in a simple way, create effects, transitions, movements, animations, etc

Hide and Show

The method hide allows you to hide an element

To be able to re-make it visible we can use the method show

In the above example when the button is clicked with id hide has used the method to hide a parameter that indicates the speed (in milliseconds) to hide the paragraph with id part01

When you press the button with id show it has been used the show method with a parameter that indicates the speed (in milliseconds) to display the paragraph with id part01

Fading

It is similar to Toggle, since the element appears or disappears, however it does gradually

We will use this example to test the different methods of fadding

FadeIn

Allows that a hidden item appears

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

FadeOut

Allows an element to be hidden

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

FadeToggle

Allows altenar between the effects of fadeIn and fadeOut on a element

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

Sliding

It allows us to move items to show up or down

We will use this example to test the different methods of sliding

SlideDown

It moves down the element

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

SlideUp

Move element up

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

SlideToggle

Allows altenar between the effects slideDown and slideUp to the element

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

Animations

It is also possible to create custom animations with the method animate() with the following syntax:

The first parameter defines a set of CSS_Properties, enclosed between the symbols { and }, that are to be modified

The second indicates the speed(in milliseconds) or the values ‘slow’ or ‘fast’

We will use this example to test various ways of doing animations

Modify the HTML in the previous example to add this script, in which we modified a single property

Modify the HTML in the previous example to add this script, in which we modified several properties

Modify the HTML in the previous example to add this script, in which we modified several properties using relative values

We modified the HTML from the previous example to add this script, in which we modified several properties by running several consecutive animations one after another

Ajax

AJAX

Ajax (asynchronous Javascript and XML) allows you to upload content from a web page and display it without having to recharge it

Almost any current web page uses this technology: Gmail, Google Maps, YouToube, Facebook, etc

To accomplish this, Ajax builds a layer of additional process between the website and our server

In this way, the requests to the server will be asynchronous, without interfering with the loading process or the actions of the user

While on the browser side, the user can perform actions at any time without being paralyzed waiting for a response from the server

The update of elements is performed through the layer Ajax, dynamically and continuously while the user is still using the page

Elements that make up Ajax

Now let's examine each of the different elements that make up an Ajax application

XMLHTTPRequest

The object XMLHTTPRequest is supported by all modern browsers, starting with Internet Explorer 5+, in addition to Mozilla, Firefox, Konqueror, Opera and Safari

It is supported by a wide variety of platforms, including Microsoft Windows, UNIX / Linux, and Mac OS X

The purpose of this object is to allow Javascript the formulation and sending of HTTP requests to the server

Before using the object, we must call it with its constructor and adapt it according to the peculiarities of each browser

Microsoft was the first to introduce the object, with an implementation of the same as an ActiveX

The rest of browsers have included a native version of the same though implementandolo as a Javascript object

Given that the object depends on what browser and what operating system it is able to use it, you must adapt the code to instancie correctly

In the example above shows how it would be the call of the constructor depending on the browser if using pure Javascript code

If we use the object navigator that stores information about the browser, we could do a conditional comparison according to the type of browser you just using it as a variable:

Properties of the object

  • onreadystatechange

    determines which event handler will be called when you change the property readyState the object

  • readyState

    is an integer value that reports the status of the request:

    • 0 = uninitialized
    • 1 = cárgandose
    • 2 = loaded
    • 3 = interactive
    • 4 = completed
  • responseText

    text string returned by the server that represents the data of the request

  • responseXML

    XML document returned by the server that represents the data of the request

  • status

    code HTTP status returned by the server

  • statusText

    text string returned by the server with a description of the state

Methods of the object

  • abort()

    stops the current request

  • getAllResponseHeaders()

    returns a text string containing all the headers

  • getResponseHeader(x)

    returns a text string with the value of the header x

  • open(‘method’, ‘URL’, ‘a’)

    specifies if the method of the request is GET or POST, the destination URL and if the request should be handled asynchronously (if it is true) or synchronous (if it is false)

  • send(content)

    sends the request with POST data of the form optional

  • setRequestHeader(‘x’, ‘y’)

    defines the parameters with a pair of variable (x) value (y) and is assigned to the header that is sent with the request

Ajax with jQuery

Thanks to jQuery, we can use a code more streamlined and simple that even allows us to forget the type of browser or the system thanks to the methods get(), post(), load() and ajax()

get()

This method requests data to the server with an HTTP GET request

GET is used basically for getting (retrieving) some data from the server

The GET method may return cached data

It has the following syntax:

  • URL

    is the destination address

  • callback

    is an optional parameter that represents the name of the function that will be executed in the event that the application is properly made

In the example we can see how when you press the item button will launch a GET request to the server, which in this case works with the PHP language, to the URL test.php and that contains the code that should be executed

If the request was executed successfully, execute the anonymous function that shows the user a warning with the content of the data parameter and status

post()

This method requests data to the server with an HTTP POST request

POST sends data for processing to a specified resource

The POST method never caches data, and is often used to send data along with the request

It has the following syntax:

  • URL

    is the destination address

  • data

    is an optional parameter that specifies the data that will be sent along with the application

  • callback

    is an optional parameter that represents the name of the function that will be executed in the event that the application is properly made

In the example we can see how when you press the item button will launch a POST request to the server, which in this case works with the PHP language, to the URL user.php and that contains the code about the user that should run

If the request was executed successfully, execute the anonymous function that shows the user a warning with the content of the data parameter and status

load()

This method gets content from the server and adds them to an element of our page

It has the following syntax:

  • URL

    is the destination address

  • data

    is an optional parameter that specifies the data that will be sent along with the application

  • callback

    is an optional parameter that represents the name of the function that will be executed in the event that the application is properly made

    This function must have the following mandatory parameters:

    • responseTxt

      the content of response in case of success

    • statusTxt

      is a text string with the status of the petition, you can be one of the following values:

      • abort
      • error
      • notmodified
      • parsererror
      • success
      • timeout
    • xhr

      contains the object XHTMLRequest, which provides us with additional information about the Ajax request

In the example we can see how when it is finished loading the DOM will load the content of datos.html in the element with the id div01in particular, the elements within this file that have the id p1

When you use a selector for the HTML elements that we want to load, jQuery the filter without problems, as we have seen in this example

We can also load other file types, such as for example .txtbut we have to take into account that has to be carried out by the HTTP protocol and not directly from disk (with file://)

In the event that the request fails, we would see The content will be loaded hereinstead of the loaded content

ajax()

This method performs a request asynchronous HTTP

It has the following syntax:

  • URL

    is an optional parameter that sets out the destination address, if not specified it will add it within the parameter settings as another value more

  • settings

    specifies the data that will be sent along with the application

    Can be specified default values for all Ajax requests using the method ajaxSetup()

In the example we can see that it will launch a POST request to the server, which in this case works with the PHP language, to the URL teams.php and that contains the code that should be executed

In dataType has been specified that it will receive an object of type JSON and it will use the data provided by the method called get_groups with the parameters league that picks up its value from the element with id team-league and season that picks up its value from the element with id team-season

We have included the callback hooks beforeSend,, error, dataFilter, success and complete for ilustar the order in which they are called

Only has code to errorin case of failure of the request and to successin the case that it is correct

If you are running the callback hook successis recorreran all the data received in JSON format and will be added to the element with id team-group that corresponds to an option element of a select field, this new element will be added at the end of the existing

Parameters settings

  • accepts

    assigns a dataType of type MIME, which will be sent in the header of the request

    This header informs the server what type of response will be accepted

    In the example you have assigned a MIME type to work with data in the XML format and the server will return the ‘mycustomtype‘ as we have specified

    To be able to work correctly with the new type, it is necessary to use converters to convert it correctly to the format that we want to return

  • async

    by default, all requests are sent asynchronous (set to true this is the default)

    To configure them synchronously you must asignarsele as false

    Applications cross-domain and the dataType: ‘jsonp’ do not support operations synchronous

    Keep in mind that the requests are synchronous may temporarily lock the browser, disabling any actions while the request remains active

    As of jQuery 1.8 , the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the callback success, error or complete in place of the corresponding methods of the object jqXHR such as jqXHR.done()

  • beforeSend,

    it is a method of event the Ajax that is executed before the call request that can be used to modify the object jqXHR (in jQuery 1.4.x, XMLHTTPRequest) before it is sent

    Can be used to add custom headers, etc

    The objects jqXHR and settings are passed as arguments

    If it returns false, the application will be cancelled

    As of jQuery 1.5, the options are all calls, regardless of the type of application

  • cache

    if it is set to falsewill force the browser not to cache the pages requested

    Established in false will only work correctly with HEAD requests, and GET if it has been added ‘_ = {timestamp}‘ to GET parameters

    The parameter is not required for other types of requests, except in IE8 when a POST to a URL that has already been requested with GET

  • complete

    it is a method of event the Ajax that is executed after the events success and error

    This method passes two arguments: jqXHR (in jQuery 1.4.x, XMLHTTPRequest) and a text string with the status of the application (‘success‘, ‘notmodified‘, ‘nocontent‘, ‘error‘, ‘timeout‘, ‘abort‘, or ‘parsererror‘)

    As of jQuery 1.5, you can accept multiple requests and each one will turn

  • contents

    determines how jQuery will parse the response, given its content type, supports regular expressions (added in jQuery 1.5)

  • contentType

    type of content with which to send the data to the server
    The default value is ‘application/x-www-form-urlencoded; charset=UTF-8

    If you pass explicitly a content type to $.ajax(), will always be sent to the server (even if no data is sent)

    From jQuery 1.6 you can pass false to tell jQuery not to set any content-type header

    The W3C specification XMLHttpRequest it says that the charset should always be UTF-8; specifying another charset will not obligaráal browser to change the encoding

    For requests to cross-domain, when it is other than ‘application/x-www-form-urlencoded‘, ‘multipart/form-data‘, or ‘text/plain‘, the browser will perform checks prior to sending the request to the server

  • context

    context for all responses of the request, by default, the context is an object that represents the settings used in the call ($.ajaxSettings along with the settings you've entered with $.ajax() )

    For example, specifying a DOM element as the context will make its context to the event callback complete is:

  • converters

    method to convert the returned value to the format that we need them as answer (added in jQuery 1.5)

  • crossDomain

    is used to force a request crossDomain (such as JSONP) on the same domain, you must set the value of crossDomain to true

    This allows, for example, the redirection from the server to another domain (added in jQuery 1.5)

  • data

    data that is to be send to the server, will be converted to a query string

    Will be added to the url in GET requests

    Query the option processData to avoid this automatic process

    In the case of an array, jQuery serialize multiple values with the same key depending on the value of the setting of traditional

  • dataFilter

    method that will be used to handle the response data from the raw XMLHttpRequest

    It accepts two parameters:

    • data

      the raw data returned by the server

    • dataType
  • dataType

    type of data expected by the server

    If none is specified, jQuery will try to inferirlo based on the MIME type of the response (MIME type XML generate XML, in 1.4 JSON will generate a JavaScript object, in 1.4 script will execute the script, and any other type will be returned as a string)

    The available types (and the result passed as the first argument to your callback is accepted) are:

    • xml

      returns an XML document that can be processed via jQuery

    • html

      returns an HTML document as text without format; the labels of included script will be evaluated when inserted in the DOM

    • script

      evaluates the response as JavaScript and it is returned as plain text

      Disables caching by adding a parameter in the query string ‘_ = {timestamp}‘ to the URL unless the cache option is set as true

      In this case the POST will be converted to GET to the requests of remote-domain

    • json

      evaluates the response as JSON and returns a JavaScript object

      The json requests callback placeholder, for example ‘?callback=?‘, is made using JSONP unless the application includes jsonp: false in the configuration of the request

      The JSON data is parsed in a strict sense; any JSON with incorrect format will be rejected and will throw an error

      As of jQuery 1.9, we also reject the answers empty; the server should return a response null or {} in its place (see json.org for more information on the correction of the JSON format)

    • jsonp

      load in a block-JSON-using JSONP

      Adds ‘?callback=?‘ at the end of your URL to specify the callback of the request

      Disables caching by adding a parameter in the query string ‘_ = {timestamp}‘ to the URL unless the cache option is set as true

    • text

      string of text without format

    • multiple values separated by spaces

      as of jQuery 1.5, it is possible to convert a dataType received in the header Content-Type the necessary

      For example, if you want a string of text to be treated as XML, use ‘text xml

      You can also make a request JSONP, received as text, and will be interpreted by jQuery as XML: ‘jsonp text xml

      Similarly, the chain-shortened ‘jsonp xml‘ first, it will attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then text-to-xml

  • error

    event Ajax that will be called if the request fails

    As of jQuery 1.5, supports an array of methods and each one will be called per turn

    It will be called with requests cross-domain script and JSONP

    Receives the following parameters:

    • jqXHR

      (in jQuery 1.4.x, XMLHttpRequest)

    • text string

      describes the type of error that occurred

      Supports the following values:

      • null

        it is not a string, it is the literal null

      • timeout
      • error
      • abort
      • parsererror
    • errorThrown

      subject to certain exceptions, it is optional

      When an HTTP error occurs, errorThrown a party receives text of the HTTP status, such as ‘Not Found‘ or ‘Internal Server Error‘ with this parameter we can replace your options and configure it

  • global

    enables the use of several global events and Ajax
    Its default value is true

    Use false to avoid that the global events ajaxStart or ajaxStop are assets

  • headers

    additional headers sent along with the request using XMLHttpRequest, able to modify the object by changing the value X-Requested-With: XMLHttpRequest

    It is also possible to change the value with the event, Ajax beforeSend, (added in jQuery 1.5)

  • ifModified

    check the value of header Last-Modified to see if the last request was successful

    Its default value is falseignore the header

    Since jQuery 1.4, it also verifies the value of ‘etag‘ specified by the server to catch unmodified data

  • isLocal

    allows the current environment to be recognized as ‘local‘ (for example, the file system), even if jQuery does not recognize it as such by default

    The following protocols are currently recognized as local:

    • file
    • *-extension
    • widget

    If the configuration of isLocal needs to be modified, it is recommended to do it with the method $.ajaxSetup() (added in jQuery 1.5.1)

  • jsonp

    overrides the response function of the requests JSONP

    This value will be used in place of the ‘callback‘ in the query string of the url when you add ‘callback=?

    For example {jsonp:’onJSONPLoad’} return to the server ‘onJSONPLoad=?

    As of jQuery 1.5, setting jsonp to false to avoid that jQuery add the string ‘?callback‘ to the URL or attempting to use ‘=?‘ to perform the transformation

    In this case, you must explicitly set the configuration to jsonpCallback

    For example, { jsonp: false, jsonpCallback: ‘callbackName’ }

    For safety reasons, if the target receptor is not trusted, it is recommended to configure the property jsonp to false

  • jsonpCallback

    specifies the name of the function to return a request JSONP

    This value will be used instead of the random name automatically generated by jQuery

    It is recommended to let jQuery generate this unique name, since that will facilitate the management of requests and will be able to better control the callbacks and exceptions error

    It is possible to specify the return of the request when it is enabled the browser cache for GET requests

    As of jQuery 1.5, you can also use a function to set it up, in which case the value of jsonpCallback it is set with the return value of that function

  • method

    HTTP method that is utilirá in the request (for example ‘POST‘, ‘GET‘, ‘PUT‘ (added in jQuery 1.9.0)

  • mimeType

    mime type that overrides the mime type XHR (added in jQuery 1.5.1)

  • password

    password that will be used with XMLHttpRequest as a response to a request of authentication of HTTP access

  • processData

    by default, the data passed to data (anything that is not a string) will be processed and transformed to a query string, which will be set to the default content type ‘application/x-www-form-urlencoded

    To send a DOMDocument or other data is not processed, set it to false

  • scriptAttrs

    defines additional attributes for use in requests ‘script‘ or ‘jsonp

    Where:

    • key

      represents the name of the attribute

    • value

      is the value of the attribute

    When you receive this object, you will force the use of the script tag transport

    For example, can be used to declare attributes nonce, integrity or crossorigin to meet the requirements of the security policy of the content (added in jQuery 3.4.0)

  • scriptCharset

    only used with the ‘script‘ transport

    Defines the attribute charset in the script tag used in the request

    It is used when the character set on the local page is not the same as that of the remote script

    Alternatively, the attribute charset it can be defined with scriptAttrs, which will also ensure the use of transport ‘script

  • statusCode

    numeric codes HTTP and functions that will be called as a response to that code

    For example, when the response status is a 404, it will display a prompt to the user:

    If the request is successful, the status code of the function will take the same parameters as the return of the petition to be correct; if an error occurs (including the redirection 3xx), it will take the same parameters as the error callback (added in jQuery 1.5 )

  • success

    event Ajax call if the request is correct

    It has the following arguments:

    • data

      data returned by the server, formatted according to the parameter dataType or the callback function dataFilterif one has been defined

    • textStatus

      text string that describes the state

    • jqXHR

      (in jQuery 1.4.x, XMLHttpRequest)

    As of jQuery 1.5, supports an array of methods and each one will be called per turn

  • timeout

    sets a timeout (in milliseconds) for the request
    The value 0 means no timeout

    This will override any global timeout set with the $.ajaxSetup()

    The timeout period begins when the call is made to $.ajax

    If there are other requests in progress and the browser has no connections available, it is possible that any request to time out before it can be sent

    As of jQuery 1.4.x, the object XMLHttpRequest it will take the state to invalid if the request times out

    To access any field of the object can generate an exception

    Only in Firefox 3.0+, applications, script and JSONP are not cancelled by a timeout; the script will run even if it is received after a timeout

  • traditional

    the value will true if you want to use the traditional style of parameters serialized

  • type

    alias for method. Use type for versions of jQuery prior to 1.9.0

  • url

    string that contains the URL to which to send the request

  • username

    user name that will be used with XMLHttpRequest in response to a request of authentication of HTTP access

  • xhr

    return of the request to create the object XMLHttpRequest

    Its default value is ActiveXObject when available (IE), XMLHttpRequest otherwise

    Sobreescribalo to provide your own implementation of XMLHttpRequest or any improvement own

  • xhrFields

    defines the native object XHR (added in jQuery 1.5.1 )

    For example, can be used to define withCredentials to true for requests cross-domain, if necessary:

    In jQuery 1.5, the property withCredentials it is not native to XHR and therefore, the requests CORS (Cross-Origin Resource Sharing) that the require be ignored

    For this reason, I recommend using jQuery 1.5.1+ should you require to be used

PHP

PHP

PHP is a development language, based on scripts oriented Web pages

It's not a markup language like HTML could be,
XML or WML

A PHP program is executed on the server and the result sent to the browser

The result will usually generate an HTML, XML, or WML page

A being a language that runs on the server is not required that the browser supports it, but for the PHP pages work, the server are housed itself must bear

PHP history

It was originally designed in language Perl, relying on a set of binary CGIRs (a program that runs on a web server) written in the language C by the Danish-Canadian programmer Rasmus Lerdorf in 1994 to show your CV and save certain data, such as the amount of traffic your website received

On June 8, 1995, it was published under the name Personal Home Page Tools after Lerdorf combined it with its own system to process forms FI (Form Interpreter) resulting in the PHP/FI

The system Personal Home Page Tools became relatively successful because others asked Rasmus to allow them to use their programs on their own pages

Two Israeli Technion programmers, Zeev Suraski and Andi Gutmans, rewrote the parser analyzer in 1997 and created the basis of PHP 3, and changed its name to PHP (Hypertext Preprocessor)

PHP3 was officially released in June 1998

In 1999, Suraski and Gutmans rewrote the PHP code and created what is now known as engine Zend. Founding Zend Technologies in Ramat Gan, Israel

In May 2000, PHP 4 was launched using the new engine Zend 1.0.

In its version 4.1, released on December 10, 2001, the variables were introduced superglobals ($_GET, $_POST, $_SESSION, etc)

In version 4.2, released on April 22, 2002, they were disabled the register_globals by default

Data received by the network were no longer inserted in the global namespace, closing possible security holes in applications

In version 4.3, released on December 27, 2002, was introduced CLI (a command line interface), and the CGI (a common interface for data entry)

In version 4.4, released on July 11, 2005, man documentation pages were added to phpize and php-config

On 13 July 2007 announced the suspension of the support and development of version 4 of PHP

However the new version 4.4.8 was released with security enhancements, which was published on 13 January 2008 and subsequently version 4.4.9, which was published on 7 August 2008

He was given support critical bugs until 9 August 2008

On 13 July 2004, PHP 5 was released, using improved engine Zend Engine 2.0 (or Zend Engine 2)

In version 5.1, released on November 24, 2005, performance improvements were added with the introduction of compiler variables for your new PHP engine

In version 5.2, released on November 2, 2006, he was added native support for JSON (JavaScript Object type)

In version 5.3, released on June 30, 2009, he added:

  • support for namespaces
  • static link runtime
  • tag jump (GOTO)
  • native Closures
  • native support for PHP files (PHAR)
  • a garbage collector for circular references
  • I improved support for Windows, sqlite3 and mysqlnd as replacement libmysql as the library for extensions that worked with MySQL database
  • including fileinfo to replace the function mime_magic to improve support for international extensions MIME and remove the deprecated ereg

In its version 5.4, released on March 1, 2012, support was added for Trait and working with abbreviated syntax arrays

the following elements being considered deprecated removed: register_globals, safe_mode, allow_call_time_pass_reference, session_register(), session_unregister() and session_is_registered()

In version 5.5, released on June 20, 2013, new generators and function loops were added empty() supports expressions

the support was also abandoned for Windows XP and Windows Server 2003

In version 5.6, released on 20 August 2014, the constants were added with scalar expressions, argument lists of variable length and the exponential by the operator **

PHP 6 development was delayed because developers decided that the approach was to treat Unicode strings was not right, and began to try alternative forms before launching this version

All improvements that were planned for PHP 6, however, were added in PHP 5.3.0 (support for namespaces, static binding at runtime, lambda functions, closures, the GOTO label) and the 5.4.0 (traits, rebinding closures)

A final version 6 was finally abandoned in favor of 7

Version 7.0, was released on November 3, 2015, performance improvements and declaration of return types were added for functions

In version 7.1, released December 01, 2016 were added the return type null, the class visibility modifier const, the type nullable, pseudo type iterators, catching multiple types of exceptions

In version 7.2, released on 30 November 2017, he was added the new return type object and integration of Libsodium as an extension of the core

In version 7.3, released on December 6 2018, a flexible syntax was added for Nowdoc and Heredoc, support for references and deconstruction of arrays with list(), support for PCRE2, function hrtime()

Version 7.4 was released on October 28 2019 and reached end of life on November 28 2022

In version 8.0, released on October 26 2020, new features were added and performance was increased

In version 8.1, released on October 25 2021, the properties were added readonly, Enums, Fiber and new syntax

In version 8.2, released on December 8 2022, the attribute was added AllowDynamicProperties and creating dynamic properties was deprecated

PHP programming

To use PHP previously we install on our server

If you also want to use a database we can use PHP in conjunction with the lightweight database manager data Mysql

Or if you want a version that takes all, also included additional server as a mail server, a file server or Tomcat for Java interpreter, we can use the free distribution of Apache Friends, XAMPP

Once installed our server and the PHP module is active and configured, we can begin our programs written in PHP on our Web pages

In the example it has been embedded PHP code in the HTML itself, but this is not the only way in which we can include it

We can see that this simple CGI script is not equal to another written in other languages ​​Perl or C

Instead of writing a complete program with all the necessary commands to generate HTML output directly write the HTML code with PHP code embedded (embedded) in the same HTML, which will output (in the example, produce text we want the body tag is displayed)

To include PHP code we use special tags beginning <?php and final ?> that will allow us to enter and exit Zend PHP interpreter

We can use 4 ways to exit and enter HTML to PHP interpreter:

  • using tags beginning <?php and final ?>

  • using abbreviated version of the beginning label <? and final ?>

    As of PHP 7 this form is deprecated

  • using the ASP version of the beginning label <% and final %>

    As of PHP 7 this form is deprecated

  • attaching to the HTML document commands as a script file

We can also directly reference a file with extension .php which we can load inside anywhere in the document HTML using the function include

However, abusing this practice can force us to copy over and over again the include function in all our HTML files

For this reason it is required to use a file index.php that generates the HTML that the browser will receive and in which only the includes that the page needs will be loaded

Separation instructions

A the same as in C or Pascal languages, statements are terminated using semicolons

The final label %> also it means the end of the sentence in the event that there is no more PHP code, so in the example are equivalent

PHP Comments

PHP supports type comments C, C++ or Shell de Unix

PHP operators

PHP operators

PHP has a wide variety of operators

These operators can be distinguished into two groups: binaries, which act on two operands and unaries, which only require one operand

Thus, its general syntax is:

operand1 operator_Binary operand2

operand1 operator_unary

operator_unary operand1

Arithmetic operators

PHP supplies basic operations with the only additions of operators that return the rest of the division between the left and right operators; and the exponentiation, which allows to raise the left operator to the power of the right operator

Arithmetic operators
+ Addition
Subtraction
* Multiplication
/ Division
% Rest
** Exponentiation

Note In other languages the + operator applied to strings concatenates both strings into a single

However, in PHP to perform this operation the operator is used.

Operators of increase (++) and decrease (- -)

These operators are unary operators and they autoincremento and the autodecremento to the variable that applies to them

In addition to modifying the variable, they return the value of the variable

The operator increment or decrement can go before p behind the variable having a different meaning

If the operator is ++, it is placed after the variable is called post-increment, by first taking the value and then increasing the variable by one unit

If the ++ operator is placed before the variable, it is called pre-increment and makes that first to increase in a unit variable and then take the value

If the operator is - - it is placed after the variable, it is called post-decrement, making it take the value first and then the variable is decremented by one unit

If the operator - - is placed before the variable, it is called pre-decrement and makes that first decremente in a unit variable and then take the value

Relational operators

Are used typically in the conditional expression

The relational operators return boolean values

The operands can be numerical or strings

Relational operators
>

Greater than

<

Less than

> =

Greater than or equal to

< =

Less than or equal to

! =

Other than that

< >

It's equivalent to ! =

! = =

Different than and of the same type

= =

Like

= = = Same as y of the same type

< = >

Order Comparison (Added in PHP 7)

  • 0 when they're the same
  • -1 when the first operator is less than the second operator
  • 1 when the first operator is larger than the second
? ?

Returns its first operand if it exists and is not NULL

Otherwise it returns its second operand (Added in PHP 7)

Logical operators

The logical operands is related to the relational as they are normally the operands used are the result of expressions in relational

The resulting values are boolean

Logical operators
AND True if both are true
& & It is equivalent to AND
OR True if one of them is true
| | It's equivalent to OR
XOR True if one of them is true, but not both
! If it was true it goes to false and vice versa

Bitwise operators

The way of working of these operators is to convert to the binary operands and then operate with them bitwise

Bitwise operators
& AND
| OR
^ XOR
~ NOT
<< Propagation to the left
Shift the value to the left by entering zeros, if it goes out of range, values are lost
>> Spread to the right
Moves the value to the right entering by the left, the sign bit and eliminating the values that are out by the right

Note Propagation operators take two operands: the first is the variable to propagate and the second is the number of positions to propagate

Assignment operators

The assignment is also an operator that returns the variable modified

The assignment operator in PHP is =

The assignment operators shown below are but abbreviations that make expressions more comfortable and simple, even if they are sometimes more unreadable

Assignment operators
Operator Expression Equivalence
=

$A = $B = $C;

$D = ‘Text’;

$A = $C;

$B = $C;

$D = ‘Text’;

+ = $A + = 4; $A = $A + 4;
– = $A – = 3 * $B; $A = $A – (3 * $B);
* = $A * = 2; $A = $A * 2;
/ = $A / = 35 + $B; $A = $A / (35 + $B);
% = $A % = $B; $A = $A % $B;
. = $D . = ‘ of test’; $D = $D . ‘ of test’;
>> = $A >> = 1; $A = $A >> 1;
<< = $A << = $B; $A = $A << $B;
& = $A & = ($C + = 3); $C = $C +3;
$A = $A & $C;
^ = $A ^ = 2; $A = $A ^ 2;
| = $A | = $C; $A = $A | $C;

Other operators

Selection operator

This operator is used to execute an operation or another depending on the condition

The format is as follows:

Condition ? Exp1 : Exp2

If the condition is met it evaluates and returns the expression Exp1 if not the Exp2

We can put a just value

Example:

New operator

This operator is used to create an instance of a type of objects previously defined

The syntax to follow is as follows:

These parameters are passed to the constructor of that object in question

Operador clone

This operator will be used to create a copy of a previously defined object (which invokes, if possible, the method __clone() object)

The syntax to follow is as follows:

When cloning an object, PHP will make a shallow copy of the object's properties

Properties that are references to other variables will keep the references

Once cloning is complete, the method will be called __clone() of the new object (if the method __clone() defined), to allow you to make the necessary changes to your properties

gettype operator

This operator applied to a variable returns the type of object to which belongs the data contained by that variable

Its syntax is:

The values you can return are:

  • boolean

  • integer

  • double

    For historical reasons it is returned double also when it's kind of float

  • string

  • array

  • object

  • resource

  • NULL

  • unknown type

Preference

The operator precedence will determine the order in which they are running in a given expression

Using parentheses will check that the operations are carried out according to us we want to

In PHP the preference of the operators from highest to lowest is as follows:

Preference
Other operators clone new
Array [ ]
Exponentiation **
(in / de) crease /types ++ – – ^ (int) (float) (string) (array) (object) (bool) @
Other operators gettype
Denial !
Mul / Div / Rest * / %
Addition / Subtraction +
Spread << >>
Relational < < = > > =
Equality = = != = = = ! = = < > < = >
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
AND logic &&
A logical OR | |
Equality ? ?
Other operators ?:
Assignment = + = – = * = * * = / = . = % = & = | = ^ = >> = << =
AND logic AND
XOR lógica XOR
A logical OR OR

Php data types

Php data types

Types in PHP are a representation of data because it does not require variables to declare their type, because all types are converted automatically

Type boolean

The Boolean type simply distinguishes between two states, a success or enabled state, true value, true, and a failure or deactivated state, false value, false

Both states are not case sensitive

Typically, the result of operators that return a Boolean value are passed to a control structure

Numeric types

The numeric types can be divided into real and integer

Type integer numeric

  • Integer

    integer base 10

    Both positive and negative

  • Hexadecimal

    integer base 16

    Placed before the base number 16 0x or 0X

  • Octal

    integer base 8

    We place a zero before the number in octal

  • Binary

    integer base 2

    Placed before the base number 2 0b or 0B

Formally, the structure of integer literals is:

decimal : [1-9][0-9]* | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal : 0[0-7]+

binary : 0b[01]+

integer : [+-]?decimal | [+-]?hexadecimal | [+-]?octal | [+-]?binary

Numeric type real

The actual is made up of a whole part and the other fractional separated by a point of the previous

The fractional part can be composed by an indicator of exponent E or E followed by an integer that indicates the value of the exponent

Formally, the structure of the actual type literals is:

LNUM : [0-9]+
DNUM : ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM : [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})

  • Float

    is a floating-point numerical value

    Both positive and negative

    Its size depends on the platform, although its value can be a maximum of approximately 1.8e308, with an accuracy close to 14 decimal digits (IEEE 64 bit format)

    Additionally, rational numbers whose base 10 representation is equal to that used as a floating-point number, such as 0.1 or 0.7, do not have an exact representation as base 2 floating-point numbers, which is the internally employed basis, regardless of the mantissa size

    Therefore, they cannot be converted to binary without a small loss of precision

    Being able to result in precision errors such as floor( (0.1 + 0.7) * 10); normally it would return 8, however, it would return 7, since in its internal representation it will be 7.9999999999999991118...

    Therefore, it is not recommended to trust results with floating-point numbers and not to use the comparison of floating point numbers directly

    If you need more precision, use the mathematical functions of arbitrary precision and the functions of gmp

  • Double

    is equivalent to Float and does not provide substantial differences

    In other languages it has double precision, but in PHP it has been maintained for historical reasons and it is advisable to better use the functions that work with Float

  • NaN

    Some numerical operations may result in a value represented by the NAN constant

    This result represents an undefined or unrepresentable value using floating point calculations

    Any comparison, whether strict or not, of this value with any other value, including itself, except for TRUE, will result in FALSE

    Since it represents any number of different values, it should not be compared with other values, including itself; instead it should be checked using the function is_nan()

Type string

A string is a string of characters delimited by quotation marks

Where each character is a byte

This means that PHP only supports a set of 256 characters, hence it does not offer native support for Unicode

A string can only contain up to 2 GB in size (2147483647 bytes maximum)

A string literal can be specified in four different ways:

  • single quote

    are specified between the characters opening and closing

    To specify a single literal quote, you must escape with a backslash (\). To specify a literal backslash, duplicate (\\)

    All other instances of backslashes will be treated as a literal backslash: this means that other escape sequences that could be used, such as \r or \n, will be displayed literally as specified, instead of having any other special meaning

    Keep in mind that variables and escape statements for special characters will not be expanded when they are included in a string in single quotes

  • double quotes

    are specified between the characters " opening and " closing

    The most important feature of double string quotation marks is the fact that variable names are expanded

    PHP will interpret the following escape sequences as special characters:

    Code Description
    \n line feed (LF or 0x0A (10) in ASCII)
    \r carriage return (CR or 0x0D (13) in ASCII)
    \t horizontal tab (HT or 0x09 (9) in ASCII)
    \v vertical tabulator (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
    \e escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.4)
    \f page feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
    \\ backslash
    \$ dollar sign
    \" double quotes
    \[0-7]{1,3} the sequence of characters that matches the regular expression is a character in octal notation, which silently overflows to fit into a byte ("\400" === "\000")
    \x[0-9A-Fa-f]{1,2} the sequence of characters that matches the regular expression is a character in hexadecimal notation
    \u{[0-9A-Fa-f]+} the character sequence that matches the regular expression is a Unicode code point, which will be printed to the string as that UTF-8 representation of the code point (added in PHP 7)

    As in the simple quotation mark of a string, escaping any other character can result in the backslash also being displayed

    Prior to PHP 5.1.1, the backslash of the \{$var}

  • heredoc syntax

    are specified by the characters <<< followed by the operator EOT and ends with the EOT operator followed by the ; closing

    The closing identifier must start in the first column of the new line

    Also, the identifier must follow the same naming rules as tags in PHP: it must contain only alphanumeric characters and underscores, and must start with an alphabetic character or underscore

    It is very important to note that the line with the closing identifier must not contain any other characters except the semicolon

    The identifier must not be indented, and there should be no space or tab before or after the semicolon

    The first character before the closing identifier must be a line break defined by the local operating system

    \n UNIX systems, including Mac OS X

    In addition, the closing delimiter must also be followed by the newline

    If this rule is broken and the closing identifier is not clean, will not be considered as a closing identifier, so PHP will continue to look for one

    If no appropriate closing identifier is found before the end of the file, a parsing error will occur on the last line

    You cannot use Heredoc to initialize the properties of a class

    Since PHP 5.3, this limitation is valid only for an heredoc that contains variables, as it is possible to initialize static variables and class properties/constants

    In that version we also introduced the possibility of quoting the opening identifier in Heredoc

  • nowdoc syntax (since PHP 5.3)

    is to strings with single quotes the same as Heredoc is to strings with double quotes

    A nowdoc is specified similarly to a heredoc, but no analysis is performed within the nowdoc

    The construction is ideal for embedding PHP code or large pieces of text without having to escape them

    Share some common features with construction SGML, where a block of text is declared that is not parsed

    A nowdoc is identified by the same sequence used for heredoc, <<<, but the identifier that follows it is delimited with single quotation marks

    All rules for heredoc identifiers also apply to nowdoc identifiers, especially those that refer to the use of the closing identifier

Variable analysis

When a string is specified by double quotation marks or by heredoc, variables within that string will be parsed

There are two types of syntax:

  • simple

    is the most employed and practical

    Provides a way to embed a variable, an array value, or a property of an object within a string with minimal effort

  • complex

    can be recognized by the keys that delimit the expression

Simple syntax

If a dollar sign ($) is found, the analyzer will take the largest number of symbols to form a valid variable name

Delimiting the variable name with braces allows you to explicitly specify the end of the name

Similarly, you can analyze the index of an array or the property of an object

With array indices, the closing bracket (]) marks the end of the index

The same rule can be applied to object properties and simple variables

Complex syntax

Allows the use of complex expressions

Any scalar variable, array element, or object property with a representation of type string can be included through this syntax

You simply type the expression the same way it would appear outside the string, delimiting it with { and }

Given that { cannot be escaped, this syntax will be recognized only when the $ immediately follow the {

Use {\$ to get a {$ literal

Some examples to make it clearer:

With this syntax, it is also possible to access the properties of a class by using variables within a string

Functions, method calls, static class variables, and class constants within {$} work from PHP 5

However, the accessed value can be interpreted as the variable name in the scope in which the string is defined

The use of simple keys ({}) will not be used to access the value returned by functions or methods, or the values of static class constants or class variables

Arrays

An array in PHP is actually an ordered map

A map is a type of data that associates values with keys

This type is optimized for several different uses; it can be used as an array, list (vector), associative table (hash table – an implementation of a map), dictionary, collection, stack, queue, etc

Since the values of an array can be other arrays, multidimensional trees and arrays are also possible

The following syntax is used to create an array:

Where we have the function array() which serves as a constructandr and takes as parameters key/value pairs separated by commas and joined with the symbols =>

The comma after the last element of the array is optional, and can be omitted

Since with PHP 5.4 you can also use the short array syntax, which replaces the function array() with []

The key can be an integer or a string

In addition, the keys must comply with:

  • A strings containing a valid integer will be mourned to the integer type

    The key "8" will actually be stored as 8

    "08" not be converted as it's not a valid decimal integer number

  • A float will be forced to integer, which means that the decimal part be removed

    The key 8.7 actually be stored as 8

  • A Boolean be forced to integer also, namely, the true key will actually be stored as 1 and false as the key 0
  • Un null será forzado a string vacío, es decir, la clave null en realidad será almacenada como ""
  • Arrays and objects can not be used as key

    If we do, we will place a warning: Illegal offset type

  • If several elements in the declaration of the array using the same key, only the latter will be used, the others being overwritten

The key is optional and if not specified, PHP will use the increase in the key rate previously used integer greater

You can specify the key only to some elements and exclude others:

Array elements can be accessed using the syntax array[key]

Note Both brackets as the keys can be used interchangeably to access array elements ($array[42] and $array{42} will have the same result in the previous example)

Since PHP 5.4 is possible to refer to the array of the result of a call to a function or method directly

In previous versions it was only possible using a temporary variable

Since PHP 5.5 it is possible to directly reference an element of an array literal

Note Trying to access a key part of an array that is not defined is the same as accessing any other undefined variable: an error message will be issued level E_NOTICE, and the result will be NULL

An existing array can be modified by explicitly setting values ​​in it

This is done by assigning values ​​to the array, specifying the key in brackets

This can also be omitted, resulting in an empty pair of brackets ([])

If $arr does not yet exist, it is created, this being also an alternative way to create an array

However, this practice is discouraged because if $arr already contains a value (a string of a request variable), this will be in place and [] can really mean the access operator strings

It is always better to initialize variables through direct allocation

To change a certain value must be assigned a new value to that element using its key

To remove a key/value pair, call the function unset()

Iterables

A Iterable is a pseudotype introduced in PHP 7.1

Accepts any array or object that implements the interface Traversable

These two types are crossed with foreach and can be used to yield from within a generator

Iterable may be used to indicate that a function requires a set of values, but no matter the form of the whole and it will be used with foreach

If a value is not an array or an instance of Traversable, it will launch a TypeError

Parameters declared as iterable be used NULL or an array as the default

Objects

Objects consist of a set of values, properties, and a set of methods applied to those values

It is these methods that allow us to modify the state of that object, that is, the value of its properties

Let's create a academic sample object where you have the properties: Name, Surname, Age and Identity card

The instance of the object we'll create using the new operator as follows:

You can initialize all variables to have the kind we want, we will use the class constructor passing the arguments we need

From PHP 7 we can also specify the type of the argument

By keyword $this we can reference to the current object

The properties of an object can be described by other objects

The definition of methods associated with an object can be specified in the object definition

For example, for the university object we define a function that shows the student's first name, age, last name, id, and middle grades

To access the properties or methods will use the operator ->


Resources

A resource type is a special value variable, which contains a reference to an external resource

Resources are created and used by special functions

You can be obtained by the resource type function get_resource_type()

Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource that is no longer referenced is automatically detected and is released by the garbage collector

For this reason, rarely you need to free the memory manually

Note Persistent links to databases are an exception to this rule

They are not destroyed by the garbage collector to being persistent connections

Null value

PHP variables can be assigned a value indicating the empty value, this value is the value NULL

A variable is considered NULL if:

  • has been assigned the constant NULL
  • has not yet been assigned a value
  • has been destroyed function unset()

The constant NULL is insensitive to case sensitive


The conversion of data types

First of all, remember that PHP does not need type declaration

The contents of the variable will be converted automatically in the course of the programme according to its use

The type conversion scheme is based on the following principle: the associated type corresponds to that of the left operand

This is because the evaluation is done from left to right

The first expression will convert the variable $a_number in a string of characters because the operand on the left $a_string is a string of characters

This expression concatenates the two character strings and the result of x is: "742"

In contrast, the second expression converts the string $a_string in a numerical value because the operand on the left $a_number, is a number

This second expression sums the two numbers and the result of and is: 49

Type conversion cannot be done in all possible cases: certain character strings cannot be converted to number

Such conversions fail with an error

The behavior of automatic array conversion is currently undefined

Because PHP supports string indexing using offsets using the same syntax used in array indexing, the following examples are valid for all PHP versions:

Casting

Casting in PHP works the same way as in C, where the name of the desired type is enclosed in parentheses before the variable you want to force

Type Forced
(int), (integer) integer
(bool), (boolean) boolean
(float), (double), (real) float
(string) string
(array) array
(object) object
(unset) NULL (added in PHP 5)
(binary) y prefijo b binary string (added in PHP 5.2.1)

Tabs and spaces are allowed within parentheses, so the following examples are functionally equivalent:

Example of literal snapping of strings and variables to binary strings

Double quotation marks allow you to avoid forcing a variable to string, because the result is equivalent

Converting to boolean

To explicitly convert a value to the boolean type, use casting (bool) or (boolean)

However, in most cases it is unnecessary, because a value will be converted automatically if an operator, function, or control structure requires an argument of type boolean

A value can also be converted to the boolean type using the function boolval()

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the string value empty, and the string "0"
  • an array with zero elements
  • an Object with zero member variables (PHP 4 only)
  • special type NULL (including variables not set)
  • SimpleXML objects created from empty tags

Any other value is considered TRUE (including a resource variable)

Note: -1 is considered TRUE, like any other non zero (whether positive or negative)

Converting to integer

To explicitly convert a value to the integer type, use casting (int) or (integer)

However, in most cases it is unnecessary, since a value will be automatically converted if an operator, function or control structure requires an argument of type integer

A value can also be converted to the integer type by function intval()

If a resource is converted to integer, the result will be the number one resource assigned to the resource by PHP at runtime

From Booleans

FALSE will produce 0 (zero), and TRUE will produce 1 (one)

From floating point numbers

When a float is converted to an integer, the number be rounded towards zero

If the value of type float is below the limit of an integer (usually +/- 2.15e+9 = 2^31 on 32 bit platforms and +/- 9.22e+18 = 2^63 64 bit platforms other than Windows), the result is undefined, because float does not have sufficient precision to deliver the result as an exact integer

No warning is displayed, not even a warning when this happens

Note From PHP 7, instead of being indefinite and platform dependent, NaN and Infinity always be zero forcing type to integer

Note You should never turn an unknown fraction to integer, as sometimes can lead to unexpected results

From strings

If the string does not contain any of the '.', 'E', or 'E', and the numerical value is within the bounds of the integer type (as defined by PHP_INT_MAX), the string is evaluated as an integer

In all other cases it will be evaluated as a float

The value is given by the initial portion of the string

If the string starts with valid numeric data, this will be the value used

Otherwise, the value is 0 (zero)

A valid numeric data is an optional sign, followed by one or more digits

Do not wait for the code of one character by converting it to integer, as in C

Use functions ord() and chr() to convert characters to their ASCII code

From other types

The behavior of converting to integer is undefined other

Do not rely on any observed behavior, as it can change without notice

Converting to floating point number

To explicitly convert a value to the float type, use the casting (float) or (double) or (real)

However, in most cases it is unnecessary, because a value will be converted automatically if an operator, function, or control structure requires an argument of type float

A value can also be converted to the type float by function floatval()

From strings

If the string does not contain any of the '.', 'E', or 'E', and the numerical value is within the bounds of the integer type (as defined by PHP_INT_MAX), the string is evaluated as an integer

In all other cases it will be evaluated as a float

The value is given by the initial portion of the string

If the string starts with valid numeric data, this will be the value used

Otherwise, the value is 0 (zero)

Valid numeric data is an optional sign followed by one or more digits (optionally may contain a decimal point), followed by an optional exponent

The exponent is an 'e' or 'E' followed by one or more digits

From other types

The conversion is the same as if the value had been converted first to integer and then to float

Starting with PHP 5, a warning is generated if you try to convert an object to float

Converting to String

To explicitly convert a value to the string type, use the casting (string)

However, in most cases it is unnecessary, since a value will be automatically converted if an operator, function or control structure requires an argument of type string

A value can also be converted to the string type by function strval()

There is also an automatic conversion when used display functions echo or print

From Booleans

The value TRUE of the type boolean is converted to the string "1"
The value FALSE of the type boolean is converted to the string "" (the empty string)

This allows the conversion in both directions between the values ​​boolean and string types

From numbers

An integer or float is converted to a string that represents the number textually (including the exponent part for float)

Floating point numbers can be converted using exponential notation (for example 4.1E+6)

Note The character for the decimal point is defined in the script locale variable (category LC_NUMERIC). See the function setlocale()

From arrays

Arrays are always converted to the string " Array"

For this reason, echo and print can't by themselves display the contents of an array

To view a single item individually, use a construct such as echo $arr[‘foo’]

You can use the function print_r to perform the conversion and visualize the contents of the entire array

From object

Objects from PHP 4 are always converted to string "Object"

To get the class name of an object, use the function get_class()

Since PHP 5, you can use the method __toString when relevant

You can use the functions print_r or var_dump() to see more effective means of inspecting the content of these types

From resource

A resource is always converted to string with the structure "Resource id #1", where 1 is the resource number assigned to the resource by PHP during execution

Although it should not be dependent on the exact structure, because it is subject to changes during execution, it will always be unique for a given resource within the lifetime of that running script (that is, a web request or CLI process), so it won't be reused

To get the type of a resource, use the function get_resource_type()

You can use the functions print_r or var_dump() to see more effective means of inspecting the content of these types

From NULL

NULL is always converted to an empty string ""

From other types

Most PHP values can be converted to a string for permanent storage

This method is called serialization, and is performed by the function serialize()

Because the PHP engine was built with support for WDDX, PHP values can also be serialized as well formed XML text

Converting to array

From object

If you convert an object to an array, the result is an array whose elements are the properties of the object

Keys are the names of member variables, with some notable exceptions: private variables have the class name at the beginning of the variable name; protected variables have a '*' character at the beginning of the variable name

These values added at startup have null bytes on the sides

This can result in some unexpected behaviors:

From NULL

If you convert a value NULL to array, you get an empty array

From other types

For any of the types: integer, float, string, boolean, and resource, converting a value to an array results in an array with a single element, with index 0, and the scalar value that was converted

In other words, (array) $scalarValue is exactly the same as array($scalarValue)

Converting to object

If an object becomes an object, it is not modified

From other types

If a value of any other type becomes an object, a new instance of the built-in stdClass class is created

If the value is NULL, the new instance will be empty

An array becomes an object with the properties named as keys and the corresponding values, with the exception of the numeric keys, which will be inaccessible unless they are traversed

Converting to resource

Since the resource variables contain special managers to open files, connections to databases, graphic areas for images and the like, the conversion to resource type is meaningless

Conversting to NULL

Note This feature has been declared deprecated as of PHP 7.2 and its use is totally discouraged

Converting a variable to null using (unset) $var will not delete the variable or destroy its value

It will only return one value NULL

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