You are engaged in the creation and promotion of a website under the control of CMS Joomla and you suddenly have a need to remake to your taste and mood designing the material by editing the standard templates of the com_content component? The component is responsible for generating content. Let's take a look at the structure of the component itself.

Location of the standard material template

Original component files com_content located in components\com_content\views\View\tmpl. If the component files are copied to the \templates\template\html\com_content\ directory that you use, then the material template will be taken from the files of this folder.

Template directories and files

The template location directory contains five folders for generating views.

folder archive

  • Archive output template folder. This article is not considered, rarely used by anyone. The structure is similar to the folders described below;

folder article - Material

folder front page - Main page

  • default.php Same principle as category\blog.php;
  • default_item.php Same principle as category\blog_item.php;
  • default_links.php Same principle as category\blog_links.php;

folder section - Chapter

  • blog.php Section blog template. Same principle as category\blog.php;
  • blog_item.php A template for a separate article from the blog section. Same principle as category\blog_item.php;
  • blog_links.php Template for presenting links under the section blog. Same principle as category\blog_links.php;
  • default.php Standard section template. Displays the title of the category, its description, the number of elements. After clicking on the category title, the page is processed by category\default.php;

An example of editing a template. Displays the number of views of the material.

Let's say we want print the number of hits separate material from category blog. To do this, edit the category\blog_item.php template. The code for inserting information about hits will be as follows:

item->hits ?>

Now you need to find in the category\blog_item.php template file the place where to insert this code. For example, before displaying the date of the last editing of the material. Looking for the line:

item->modified) !=0 && $this->item->params->get("show_modify_date")) : ?>

And before it, insert a line with the code.

Example listing categories in multiple columns .

See involuntarily ... Dictionary of Russian synonyms and expressions similar in meaning. under. ed. N. Abramova, M .: Russian dictionaries, 1999. unconsciously by instinct, without realizing it, spontaneously, panicky, instinctively, without realizing it, without realizing it, ... ... Synonym dictionary

Unaccountably, instinctively, automatically, spontaneously, blindly. Cm … Synonym dictionary

Involuntarily, unconsciously, unconsciously, instinctively, mechanically, mechanically, blindly, spontaneously; accidentally, unintentionally; Willy-nilly, like it or not (volens nolens), out of necessity He had to do this because of things beyond his control... ... Synonym dictionary

Blindly, subconsciously, inwardly, without realizing it, without realizing it, spontaneously, unconsciously, without realizing it, unconsciously, mechanically, unconsciously, unconsciously, intuitively, unconsciously, sixth sense, instinctively Dictionary of Russians ... ... Synonym dictionary

See involuntarily ... Dictionary of Russian synonyms and expressions similar in meaning. under. ed. N. Abramova, M .: Russian dictionaries, 1999. blindly unconsciously, involuntarily; indistinctly, recklessly, unconsciously, spontaneously, instinctively, slavishly, unconsciously, unclearly, ... ... Synonym dictionary

adv. to the unaccountable. [Mother] wanted to turn back, but unconsciously went forward again. M. Gorky, Mother. [Judushka] begged his good friend mother to manage his estate implicitly. Saltykov Shchedrin, Gentlemen Golovlevs ... Small Academic Dictionary

UNREPORTABLE, unaccountable, unaccountable; (short masculine not used) unaccountable, unaccountable. 1. Not subject to any control, not obliged to report. He implicitly (adv.) disposed of in the shop. 2. Not dependent on reasonable considerations, ... ... Dictionary Ushakov

- (Greek). A person who is entrusted to trade without accountability, at the expense of another person. Dictionary of foreign words included in the Russian language. Chudinov A.N., 1910. ANAGALIST A person who is entrusted to trade at the expense of another person without accountability. Explanation… … Dictionary of foreign words of the Russian language

Unaccountably, unconsciously, mechanically, involuntarily, automatically, mechanically, automatically, mechanically, autopilot Dictionary of Russian synonyms. automatically see automatically Dictionary of synonyms of the Russian language. Practical guide. M .: Russian ... Synonym dictionary

See involuntarily ... Dictionary of Russian synonyms and expressions similar in meaning. under. ed. N. Abramova, M.: Russian dictionaries, 1999. instinctively, unconsciously, involuntarily; involuntarily, unconsciously, inwardly, spontaneously, spontaneously, unconsciously, blindly, ... ... Synonym dictionary

Books

  • Journey through Czechoslovakia, J. Marko, M. Peterka, Prague, 1959. Artia. With many photographic illustrations. Publisher's binding. The safety is good. The enchanted wanderer of any country of the world, delving into this beautiful book, will be able to ... Category: Notes of travelers, memoirs, research Publisher: Artia,
  • Board, or Meetings on the Sennaya, Gennady Grigoriev, Sergey Nosov, There are places in St. Petersburg that are simply phantasmogenic. Sennaya Square is one of them. "Sennaya - the cradle of phantasmagoria". The authors themselves seem surprised by what happened to them on the Sennaya. Yes and... Category: Classical and modern prose Series: Petersburg faces of our time Publisher:

Many people like to write such constructions in one form or another, everyone has come across:
foreach ($items as &$item) ( $item += 2; )
But not many are aware of the danger lurking here.
Consider an example.

Vasya Pupkin took an array, walked through it, increasing all the elements by two:
$items = array("a" => 10, "b" => 20, "c" => 30,); foreach ($items as &$item) ( $item += 2; ) print_r($items);
I looked at the dump, saw that the task was solved, and left satisfied:
Array([a] => 12[b] => 22[c] => 32)
After some time, Petrovich decided to supplement this section of code with another enumeration, adding below:
$newitems = array("a" => 10, "b" => 20, "c" => 30,); foreach ($newitems as $key=>$item) ( $newitems[$key] += 5; ) print_r($newitems);
He looked that his task was also solved, and with a sense of accomplishment closed the file:
Array ([a] => 15 [b] => 25 [c] => 35)
After some time, inexplicable bugs began to come out. Why?
Let's make var_dump($items) at the end of the code:
array(3) ( ["a"]=> int(12) ["b"]=> int(22) ["c"]=> &int(30) )
thirty! Vasya Pupkin swears that he checked. Why was it 32, and after Petrovich's code 30?

The reason lies in the ampersand. It reports that the marked data is being referenced by someone else. When leaving, Vasya did not wipe the temporary variable behind him, which he used for enumeration ($item). The variable was used with permission to change the source ("&"), which is also called "assignment by reference". He was sure that the variable would only be used inside the loop. Petrovich, using a variable with the same name, in the course of his enumeration, changed its value, and each time the place where this variable was stored changed. And it was stored in the same place as the last element of the Pupkin array.

Of course, in the case in the article exaggerated. In practice, these connections can be very complex, especially if the project is inexpensive and involves inexperienced and disparate web developers.

How can you get around this?

  • Destroy temporary variables after use, especially if they have any connection with the data being used:
    foreach ($items as &$item) $item += 2; unset($item);
  • Be careful with variables that have already been used by someone.
  • Encapsulate your actions in individual functions, methods, or namespaces.
  • Use var_dump instead of print_r and pay attention to the ampersand. To dump to a file instead of the browser, an alternative to print_r($var,true) would be:
    function dump() ( ob_start(); foreach(func_get_args() as $var) var_dump($var); return ob_get_clean(); )
In conclusion, I will say that bugs related to links can be not only in foreach. And all of them were once discussed. However, this case, judging by my experience, is so common in practice that it deserves special attention.

Many fatal and recoverable fatal errors have been converted to exceptions in PHP 7. These error exceptions inherit from the Error class, which itself implements the Throwable interface (the new base interface all exceptions inherit).

This means that custom error handlers may no longer be triggered because exceptions may be thrown instead (causing new fatal errors for uncaught Error exceptions).

A fuller description of how errors operate in PHP 7 can be found on the PHP 7 errors page . This migration guide will merely enumerate the changes that affect backward compatibility.

// PHP 5 era code that will break.
function handler (Exception $e ) ( ... )
set_exception_handler("handler");

// PHP 5 and 7 compatible.
function handler ($e ) ( ... )

// PHP 7 only.
function handler (Throwable $e ) ( ... )
?>

Internal constructors always throw exceptions on failure

Previously, some internal classes would return NULL or an unusable object when the constructor failed. All internal classes will now throw an Exception in this case in the same way that user classes already had to.

E_STRICT notices severity changes

All of the E_STRICT notices have been reclassified to other levels. E_STRICT constant is retained, so calls like error_reporting(E_ALL|E_STRICT) will not cause an error.

E_STRICT notice severity changes
Situation New level/behavior
Indexing by a resource E_NOTICE
Abstract static methods
"Redefining" a constructor Notice removed, triggers no error
Signature mismatch during inheritance E_WARNING
Same (compatible) property in two traits used Notice removed, triggers no error
Accessing static property non-statically E_NOTICE
Only variables should be assigned by reference E_NOTICE
Only variables should be passed by reference E_NOTICE
Calling non-static methods statically E_DEPRECATED

Changes to variable handling

PHP 7 now uses an abstract syntax tree when parsing source files. This has permitted many improvements to the language which were previously impossible due to limitations in the parser used in earlier versions of PHP, but has resulted in the removal of a few special cases for consistency reasons, which has resulted in backward compatibility breaks. These cases are detailed in this section.

Changes to the handling of indirect variables, properties, and methods

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluation has changed.

Old and new evaluation of indirect expressions
expression PHP 5 interpretation PHP 7 interpretation
$$foo["bar"]["baz"] $($foo["bar"]["baz"]) ($$foo)["bar"]["baz"]
$foo->$bar["baz"] $foo->($bar["baz"]) ($foo->$bar)["baz"]
$foo->$bar["baz"]() $foo->($bar["baz"])() ($foo->$bar)["baz"]()
Foo::$bar["baz"]() Foo::($bar["baz"])() (Foo::$bar)["baz"]()

Code that used the old right-to-left evaluation order must be rewritten to explicitly use that evaluation order with curly braces (see the above middle column). This will make the code both forwards compatible with PHP 7.x and backwards compatible with PHP 5.x.

var_dump (1 >> - 1 );
?>

Fatal error: Uncaught ArithmeticError: Bit shift by negative number in /tmp/test.php:2 Stack trace: #0 (main) thrown in /tmp/test.php on line 2

Out of range bitshifts

Bitwise shifts (in either direction) beyond the bit width of an integer will always result in 0. Previously, the behavior of such shifts was dependent architecture.

Changes to Division By Zero

Previously, when 0 was used as the divisor for either the divide (/) or modulus (%) operators, an E_WARNING would be emitted and false would be returned. Now, the divide operator returns a float as either +INF, -INF, or NAN, as specified by IEEE 754. The modulus operator E_WARNING has been removed and will throw a DivisionByZeroError exception.

var_dump(3/0);
var_dump(0 / 0 );
var_dump(0 % 0 );
?>

Output of the above example in PHP 5:

Warning: Division by zero in %s on line %d bool(false) Warning: Division by zero in %s on line %d bool(false) Warning: Division by zero in %s on line %d bool(false)

Output of the above example in PHP 7:

Warning: Division by zero in %s on line %d float(INF) Warning: Division by zero in %s on line %d float(NAN) PHP Fatal error: Uncaught DivisionByZeroError: Modulo by zero in %s line %d

$str = "0xffff" ;
$int = filter_var ($str , FILTER_VALIDATE_INT , FILTER_FLAG_ALLOW_HEX );
if (false === $int ) (
throw new Exception("Invalid integer!" );
}
var_dump($int ); // int(65535)
?>

\u( may cause errors

Due to the addition of the new Unicode codepoint escape syntax , strings containing a literal \u( followed by an invalid sequence will cause a fatal error. To avoid this, the leading backslash should be escaped.

Removed functions

Removed INI directives

xsl.security_prefs

The xsl.security_prefs directive has been removed. Instead, the XsltProcessor::setSecurityPrefs() method should be called to control the security preferences on a per-processor basis.

Other backward incompatible changes

New objects cannot be assigned by reference

The result of the new statement can no longer be assigned to a variable by reference:

classC()
$c =& new C ;
?>

Output of the above example in PHP 5:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

Output of the above example in PHP 7:

Parse error: syntax error, unexpected "new" (T_NEW) in /tmp/test.php on line 3

Invalid class, interface and trait names

The following names cannot be used to name classes, interfaces or traits:

  • bool
  • int
  • float
  • string
  • NULL
  • TRUE
  • FALSE

Furthermore, the following names should not be used. Although they will not generate an error in PHP 7.0, they are reserved for future use and should be considered deprecated.

  • object
  • mixed
  • numerical

ASP and script PHP tags removed

Support for using ASP and script tags to delimit PHP code has been removed. The affected tags are:

Removed ASP and script tags
opening tag Closing tag
<% %>
<%= %>

Calls from incompatible context removed

Previously deprecated in PHP 5.6 , static calls made to a non-static method with an incompatible context will now result in the called method having an undefined $this variable and a deprecation warning being issued.

class A (
public function test() ( var_dump($this); )
}

// Note: Does NOT extend A
class B (
public function callNonStaticMethodOfA() ( A::test(); )
}

(new B)-> callNonStaticMethodOfA();
?>

Output of the above example in PHP 5.6:

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8 object(B)#1 (0) ( )

Output of the above example in PHP 7:

Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8 Notice: Undefined variable: this in /tmp/test.php on line 3 NULL

yield is now a right associative operator

The yield construct no longer requires parentheses, and has been changed to a right associative operator with precedence between print and => . This can result in changed behaviour:

echo yield - 1 ;
echo (yield ) - 1 ;
// And is now interpreted as
echo yield (- 1 );

Yield $foo or die;
// Was previously interpreted as
yield($foo or die);
// And is now interpreted as
(yield $foo ) or die;
?>

Parentheses can be used to disambiguate those cases.

Functions cannot have multiple parameters with the same name

It is no longer possible to define two or more function parameters with the same name. For example, the following function will trigger an E_COMPILE_ERROR:

function foo ($a , $b , $unused , $unused ) (
}
?>

Functions inspecting arguments report the current parameter value

func_get_arg(), func_get_args(), debug_backtrace() and exception backtraces will no longer report the original value that was passed to a parameter, but will instead provide the current value (which might have been modified).

function foo ($x ) (
$x++;
var_dump(func_get_arg(0));
}
foo(1); ?>

Output of the above example in PHP 5:

Output of the above example in PHP 7:

Switch statements cannot have multiple default blocks

It is no longer possible to define two or more default blocks in a switch statement. For example, the following switch statement will trigger an E_COMPILE_ERROR:

switch(1 ) {
default:
break;
default:
break;
}
?>

JSON extension replaced with JSOND

The JSON extension has been replaced with JSOND, causing three minor BC breaks. Firstly, a number must not end in a decimal point (i.e. 34. must be changed to either 34.0 or 34 ). Secondly, when using scientific notation, the e exponent must not immediately follow a decimal point (i.e. 3.e3 must be changed to either 3.0e3 or 3e3). Finally, an empty string is no longer considered valid JSON.

Internal function failure on overflow

Previously, internal functions would silently truncate numbers produced from float-to-integer coercions when the float was too large to represent as an integer. Now, an E_WARNING will be emitted and NULL will be returned.

Fixes to custom session handler return values

Any predicate functions implemented by custom session handlers that return either FALSE or -1 will be fatal errors. If any value from these functions other than a boolean, -1 , or 0 is returned, then it will fail and an E_WARNING will be emitted.

Sort order of equal elements

The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

Don't rely on the order of elements which compare as equal; it might change anytime.

Misplaced break and switch statements

break and continue statements outside of a loop or switch control structure are now detected at compile-time instead of run-time as before, and trigger an E_COMPILE_ERROR.

No matter how much we use PHP, some features still pop up that we have not even heard of. Some of them would be very useful to us. I've created a short list of useful features that every PHP programmer should have in their arsenal.

1. Creating functions with a variable number of arguments

You probably already know that PHP allows us to create functions with optional arguments. Now I will show a function in which the number of arguments can change from case to case.

But first, let's remember how we create functions in the usual way:

// function with two optional parameters function foo($arg1 = "", $arg2 = "") ( echo "arg1: $arg1\n"; echo "arg2: $arg2\n"; ) foo("hello", "world"); /* output: arg1: hello arg2: world */ foo(); /* output: arg1: arg2: */

Now let's look at how you can write a function with an unlimited number of arguments. For this, the func_get_args() method will be used:

// do not specify arguments function foo() ( // returns an array of passed arguments $args = func_get_args(); foreach ($args as $k => $v) ( echo "arg".($k+1)." : $v\n"; ) ) foo(); /* output nothing */ foo("hello"); /* output arg1: hello */ foo("hello", "world", "again"); /* output arg1: hello arg2: world arg3: again */

2. Use Glob() to Find Files

Often the function names speak for themselves. The same cannot be said for the glob() function.

Without going into details, its functionality is similar to the scandir() method. It allows you to find the required file by the pattern:

// find all php files $files = glob("*.php"); print_r($files); /* output: Array ( => phptest.php => pi.php => post_output.php => test.php) */

To find files of several types, you need to write like this:

// find all php and txt files $files = glob("*.(php,txt)", GLOB_BRACE); print_r($files); /* output: Array ( => phptest.php => pi.php => post_output.php => test.php => log.txt => test.txt) */

You can also specify the path in the template:

$files = glob("../images/a*.jpg"); print_r($files); /* output: Array ( => ../images/apple.jpg => ../images/art.jpg) */

To get the full path to a document, use the realpath() method:

$files = glob("../images/a*.jpg"); // Apply the "realpath" function to each element of the array $files = array_map("realpath",$files); print_r($files); /* output: Array ( => C:\wamp\www\images\apple.jpg => C:\wamp\www\images\art.jpg) */

3. Information about the used memory

If you keep track of the amount of memory that is eaten up by your scripts, then you will probably optimize them more often.

PHP has a powerful memory tracking tool. In different parts of the script, the loads can be different. To get the value of memory used in this moment, we should use the memory_get_usage() method. To fix the maximum amount of memory used, use memory_get_peak_usage()

echo "Initial: ".memory_get_usage()." bytes \n"; /* Initial: 361400 bytes */ // give a small load for ($i = 0; $i< 100000; $i++) { $array = md5($i); } // и ещё for ($i = 0; $i < 100000; $i++) { unset($array[$i]); } echo "Final: ".memory_get_usage()." bytes \n"; /* Final: 885912 bytes */ echo "Peak: ".memory_get_peak_usage()." bytes \n"; /* Peak: 13687072 bytes */

4. Processor Information

To do this, you need to use the getrusage() method. But note that this feature will not work on Windows.

Print_r(getrusage()); /* prints Array ( => 0 => 0 => 2 => 3 => 12692 => 764 => 3864 => 94 => 0 => 1 => 67 => 4 => 0 => 0 => 0 => 6269 => 0) */

The picture outlined above will be clear to those who have experience in system administration. For everyone else, we offer a decryption:

  • ru_oublock: number of block writes
  • ru_inblock: number of block reads
  • ru_msgsnd: number of sent messages
  • ru_msgrcv: number of received messages
  • ru_maxrss: maximum size of nonpaged set
  • ru_ixrss: total shared memory
  • ru_idrss: total amount of unshared data
  • ru_minflt: number of memory pages used
  • ru_majflt: number of page faults
  • ru_nsignals: number of received signals
  • ru_nvcsw: number of context switches by process
  • ru_nivcsw: number of forced context switches
  • ru_nswap: number of disk accesses during paging
  • ru_utime.tv_usec: time spent in user mode (microseconds)
  • ru_utime.tv_sec: time spent in user mode (seconds)
  • ru_stime.tv_usec: privileged mode time (microseconds)
  • ru_stime.tv_sec: privileged mode time (seconds)

In order to find out what resources of your processor are used by the script, you need the value of 'user time' (time in user mode) and 'system time' (time in privileged mode). You can get the result in both seconds and microseconds. In order to convert the total number of seconds into decimal number, you need to divide the microseconds value by 1 million and add seconds to the value.

Somehow confusing. Here is an example:

// rest 3 seconds sleep(3); $data = getrusage(); echo "User time: ". ($data["ru_utime.tv_sec"] + $data["ru_utime.tv_usec"] / 1000000); echo "System time: ". ($data["ru_stime.tv_sec"] + $data["ru_stime.tv_usec"] / 1000000); /* prints User time: 0.011552 System time: 0 */

Although the script took about 3 seconds to complete, the processor was not heavily loaded. The matter is that at a call (sleep) the script practically does not consume resources of the processor. In general, there are many tasks that take a significant amount of time, but do not use the processor. For example, waiting for disk-related operations. So you don't always use CPU time in your scripts.

Here's another example:

// walk 10 million times for($i=0;$i<10000000;$i++) { } $data = getrusage(); echo "User time: ". ($data["ru_utime.tv_sec"] + $data["ru_utime.tv_usec"] / 1000000); echo "System time: ". ($data["ru_stime.tv_sec"] + $data["ru_stime.tv_usec"] / 1000000); /* выводит User time: 1.424592 System time: 0.004204 */

The script took 1.4 seconds of CPU time. In this case, system call times are generally low.

The privileged mode time (System Time) is the time that the processor spends executing system requests to the kernel on behalf of the program. Example:

$start = microtime(true); // call microtime every 3 seconds while(microtime(true) - $start< 3) { } $data = getrusage(); echo "User time: ". ($data["ru_utime.tv_sec"] + $data["ru_utime.tv_usec"] / 1000000); echo "System time: ". ($data["ru_stime.tv_sec"] + $data["ru_stime.tv_usec"] / 1000000); /* выводит User time: 1.088171 System time: 1.675315 */

Now the system time has been spent much more than in the previous example. All thanks to the microtime () method, which uses system resources.

However, it should be noted that the displayed time may not be accurate, because. at this point in time, processor resources are also being used by other programs, which may result in a small error.

5. Magic constants

There are many magic constants in PHP such as current line number (__LINE__), file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespaces (__NAMESPACE__).

We will not consider them all. Let's just look at a couple:

// this script depends on the current location of the file and // can cause problems if used from different directories require_once("config/database.php"); // this script won't cause problems require_once(dirname(__FILE__) . "/config/database.php");

Use __LINE__ when debugging scripts:

// code // ... my_debug("some debug message", __LINE__); /* output Line 4: some debug message */ // more code // ... my_debug("another debug message", __LINE__); /* output Line 11: another debug message */ function my_debug($msg, $line) ( echo "Line $line: $msg\n"; )

6. Generation of unique IDs

There are times when you need to generate a unique string. Many times I have seen that md5() function is used to solve this problem:

// generate a random string echo md5(time() . mt_rand(1,1000000));

But in fact, PHP has a special uniqid() function for this purpose.

// generate a random string echo uniqid(); /* outputs 4bd67c947233e */ // one more time echo uniqid(); /* prints 4bd67c9472340 */

With the naked eye, you can see that the first characters are similar to say the least ... This is due to the fact that this method uses server time to generate characters. It's even useful, because. all generated values ​​are obtained in alphabetical order, which makes it possible to quickly sort them.

In order to reduce the chances of getting a duplicate, we can add a prefix or use a second parameter (increase the number of characters):

// prefixed with echo uniqid("foo_"); /* output foo_4bd67d6cd8b8f */ // with second parameter echo uniqid("",true); /* outputs 4bd67d6cd8b926.12135106 */ // both echo uniqid("bar_",true); /* prints bar_4bd67da367b650.43684647 */

This method generates strings smaller than md5, so you can save space.

7. Serialization

Have you ever had to store complex data in a database or file? In order to convert an object to a string, PHP provides a special function.

Generally speaking, these methods are 2: serialize() and unserialize()

// complex array $myvar = array("hello", 42, array(1,"two"), "apple"); // convert to string $string = serialize($myvar); echo $string; /* output a:4:(i:0;s:5:"hello";i:1;i:42;i:2;a:2:(i:0;i:1;i:1;s :3:"two";)i:3;s:5:"apple";) */ // get the original value $newvar = unserialize($string); print_r($newvar); /* prints Array ( => hello => 42 => Array ( => 1 => two) => apple) */

This is how these functions work. However, due to the rapid growth in popularity of JSON, 2 methods json_encode() and json_decode() were added in PHP 5.2. Their work is similar to serialize():

// complex array $myvar = array("hello", 42, array(1,"two"), "apple"); // convert to string $string = json_encode($myvar); echo $string; /* prints ["hello",42,,"apple"] */ // restore the original value $newvar = json_decode($string); print_r($newvar); /* prints Array ( => hello => 42 => Array ( => 1 => two) => apple) */

This option is more compact and compatible with other languages ​​such as JavaScript. However, when working with very sophisticated objects, data loss can occur.

8. String Compression

When we talk about compression, archive files in ZIP format immediately come to mind. PHP provides the ability to compress long lines without any files.

In the following example, we will demonstrate the operation of the gzcompress() and gzuncompress() functions:

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut elit id mi ultricies adipiscing. Nulla facilisi. Praesent pulvinar, sapien vel feugiat vestibulum, nulla dui pretium orci, non ultricies elit lacus quis ante. Lorem ipsum dolor sit amet , consectetur adipiscing elit. Aliquam pretium ullamcorper urna quis iaculis. Etiam ac massa sed turpis tempor luctus. Curabitur sed nibh eu elit mollis congue. Praesent ipsum diam, consectetur vitae ornare a, aliquam a nunc. In id magna pellentesque tellpis posuere seded non mi metus, at lacinia augue. Sed magna nisi, ornare in mollis in, mollis sed nunc. Etiam at justo in leo congue mollis. Nullam in neque eget metus hendrerit scelerisque eu non enim. Ut malesuada lacus eu nulla bibendum id euismod urna sodales . "; $compressed = gzcompress($string); echo "Original size: ". strlen($string)."\n"; /* prints Original size: 800 */ echo "Compressed size: ". strlen($compressed)."\n"; /* output Compressed size: 418 */ // return $original = gzuncompress($compressed);

We can reduce the amount of text by 50%. For the same purpose, you can use the gzencode() and gzdecode() methods, which use a different compression algorithm.

9. Run before completion

PHP has a register_shutdown_function() function that allows you to execute some code before the script exits.

Let's say you want to find out some information... Script running time:

// get start time $start_time = microtime(true); // some operations // ... // print the running time echo "execution took: ". (microtime(true) - $start_time). "seconds.";

At first glance, this may seem like a trivial task. For these purposes, you can put the code at the end of the file. However, if the exit() function is executed somewhere before, this code will never work. Also, it will not work if there is an error on the page or the user interrupts the page loading (by clicking on the appropriate button in his browser);

When using the register_shutdown_function() method, the code will be executed anyway:

$start_time = microtime(true); register_shutdown_function("my_shutdown"); function my_shutdown() ( global $start_time; echo "execution took: ". (microtime(true) - $start_time). " seconds."; )

Conclusion

PHP is a whole planet that never ceases to amaze us with its content. What do you think of these features?