Since PHP 5 is a set of classes and interfaces that allow us to obtain information about the classes, functions, methods, attributes and objects. This package allows us, for example, to know how many parameters receives a function, and how many are required ... One example of how to use this
/**
* This function repeats
*
* @param string $text
* @param integer $times
*/
function repeat($text, $times = 2) {
return str_repeat($text, $times);
}
$reflection = new ReflectionFunction('repeat');
echo 'User defined: ' , $reflection->isUserDefined() , "\r\n";
echo 'Documentation: ' , $reflection->getDocComment() , "\r\n";
echo '# Params: ' , $reflection->getNumberOfParameters() , "\r\n";
foreach ($reflection->getParameters() as $parametro)
{
echo 'Parameter "' , $parametro->getName() , '" ' , ($parametro->isOptional() ? '' : 'no ') , 'is optional' , "\n";
echo 'By default: ' , ($parametro->isDefaultValueAvailable() ? $parametro->getDefaultValue() : 'doesn\' have any') , "\n";
}
?>
Sunday, December 16, 2007
Sunday, December 9, 2007
JSON
JSON is a format for the transmission of data useful to move from one code to another.
The most common example is to move an object or an array from PHP to JavaScript and vice versa. For this, PHP 5 provides two features that make the transfer: json_encode and json_decode. There are classes that offer a similar operation for PHP 4.
The advantage of this notation is transparency and ease with which data is transmitted. XML is an alternative which also presents its advantages. It is preferable to a series of data, if they want to consult with XQuery, but for the transmission of single data, JavaScript syntax is presented simpler.
The most common example is to move an object or an array from PHP to JavaScript and vice versa. For this, PHP 5 provides two features that make the transfer: json_encode and json_decode. There are classes that offer a similar operation for PHP 4.
The advantage of this notation is transparency and ease with which data is transmitted. XML is an alternative which also presents its advantages. It is preferable to a series of data, if they want to consult with XQuery, but for the transmission of single data, JavaScript syntax is presented simpler.
Tuesday, November 27, 2007
Whitelist vs Blacklist
When thinking about security, validation and filtering data, we have two options: either decide what to allow or what to prohibit.
On the one hand, you can use a filter to prevent XSS attacks that are based on finding a regular expression searching javascript code (either script tags or attributes onload, onclick, onmouseover...). This would be blacklist that is, put code that is unusable.
On the other hand, you can grant HTML tags type b, i, u... and eliminate all the other tags. That would be whitelist, which is, limit the user what it can do.
What is preferable?
Using a blacklist you have to think of every possible "attacks" which may accrue. This is a risk, since if we attacker thinks a method which we didn't think, we would have a huge problem. But if instead, we use a whitelist, the user could access only if he fills our standard permitted, that should be much less probable to let an attack succeed.
The whitelist disadvantage, on the other hand, is that we can filter or not to allow some information that is really valid.
Then, with a blacklist we most likely to be victims of attacks by malicious hackers, while using a whitelist can leave users without the possibility of correct entries.
Personally, I think the second option the best, because its consequences are less severe.
On the one hand, you can use a filter to prevent XSS attacks that are based on finding a regular expression searching javascript code (either script tags or attributes onload, onclick, onmouseover...). This would be blacklist that is, put code that is unusable.
On the other hand, you can grant HTML tags type b, i, u... and eliminate all the other tags. That would be whitelist, which is, limit the user what it can do.
What is preferable?
Using a blacklist you have to think of every possible "attacks" which may accrue. This is a risk, since if we attacker thinks a method which we didn't think, we would have a huge problem. But if instead, we use a whitelist, the user could access only if he fills our standard permitted, that should be much less probable to let an attack succeed.
The whitelist disadvantage, on the other hand, is that we can filter or not to allow some information that is really valid.
Then, with a blacklist we most likely to be victims of attacks by malicious hackers, while using a whitelist can leave users without the possibility of correct entries.
Personally, I think the second option the best, because its consequences are less severe.
Thursday, November 22, 2007
Mixing array with objects
The SPL extension allows us to use objects as array. One way to do this is to use the class predefined ArrayObject. Another way is to implement an interface ArrayAccess to access our data as if they were an array. An example of this
class MyArray implements ArrayAccess {
private $data;
public function __construct($array = array())
{
$this->data = $array;
}
public function offsetGet($key)
{
return $this->data[$key];
}
public function offsetSet($key, $value)
{
return $this->data[$key] = $value;
}
public function offsetExists($key)
{
return isset($this->data[$key]);
}
public function offsetUnset($key)
{
unset($this->data[$key]);
}
public function avg()
{
if (count($this->data) > 0)
{
return array_sum($this->data) / count($this->data);
}
}
}
//echo 0xFACEB00C >> 2;
$array = new MyArray(array(1, 2, 3, 4));
echo (int)isset($array[0]);
echo $array[0];
unset($array[1]);
echo (int)isset($array[1]); //throw an ugly notice
echo $array[1];
$array[1] = 4;
echo (int)isset($array[1]);
echo $array[1];
echo $array->avg();
class MyArray implements ArrayAccess {
private $data;
public function __construct($array = array())
{
$this->data = $array;
}
public function offsetGet($key)
{
return $this->data[$key];
}
public function offsetSet($key, $value)
{
return $this->data[$key] = $value;
}
public function offsetExists($key)
{
return isset($this->data[$key]);
}
public function offsetUnset($key)
{
unset($this->data[$key]);
}
public function avg()
{
if (count($this->data) > 0)
{
return array_sum($this->data) / count($this->data);
}
}
}
//echo 0xFACEB00C >> 2;
$array = new MyArray(array(1, 2, 3, 4));
echo (int)isset($array[0]);
echo $array[0];
unset($array[1]);
echo (int)isset($array[1]); //throw an ugly notice
echo $array[1];
$array[1] = 4;
echo (int)isset($array[1]);
echo $array[1];
echo $array->avg();
Tuesday, November 13, 2007
Find out if a function was called with a parameter default value
A function can have optional arguments. They are determined to give it a default value defined. For example
function test ($key, $value = null)
But how can we differentiate whether this function is called with only one parameter, or if it is called using two but the second is equal to the default?
The solution is nested but not difficult... We simply need to find how many arguments were passed to the function when called
Function test ($key, $value = null)
{
If (func_num_args ()> 1) {
Echo '$value is sent';
}
}
test('1', null);
test('1');
function test ($key, $value = null)
But how can we differentiate whether this function is called with only one parameter, or if it is called using two but the second is equal to the default?
The solution is nested but not difficult... We simply need to find how many arguments were passed to the function when called
Function test ($key, $value = null)
{
If (func_num_args ()> 1) {
Echo '$value is sent';
}
}
test('1', null);
test('1');
Thursday, November 8, 2007
Naming dates (not in english)
It is very common to the problem of wanting to put "November 8, 2007" in a language different from english... In general, a switch is used to translate the name of the month, but there is a much simpler way to do it. PHP brings the ability to configure the location, and then select "regional" settings like language, currency, numbers.
To do so, we must first set the region with setlocale and then we can use the date format with strftime
Example
setlocale(LC_ALL, 'sp');
echo strftime('%d de %B de %Y');
?>
To do so, we must first set the region with setlocale and then we can use the date format with strftime
Example
setlocale(LC_ALL, 'sp');
echo strftime('%d de %B de %Y');
?>
Monday, November 5, 2007
States game
Game:
Take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two other U.S. States.
My solution
Any suggestion?
Take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two other U.S. States.
My solution
Any suggestion?
Tuesday, October 30, 2007
Improving Pagination
Recently I discovered a method to improve the performance of a pagination in MySQL. Generally takes two queries to the database, one for bring the data and another to find out how much data is the total. What is new, though not alter the amount of queries, is that we can make the MySQL server has to process only once.
How does this work?
In the first request, in addition to requesting the data, we say to the server to calculate the total number of rows of the query, then we do a query to get this information.
mysql> SELECT * FROM t SQL_CALC_FOUND_ROWS
-> WHERE id> 100 LIMIT 10;
mysql> SELECT FOUND_ROWS ();
This is especially useful if you use an ORDER BY clause, or a complex consultation with subqueries, multiple JOIN or many calculations.
Check MySQL Manual
How does this work?
In the first request, in addition to requesting the data, we say to the server to calculate the total number of rows of the query, then we do a query to get this information.
mysql> SELECT * FROM t SQL_CALC_FOUND_ROWS
-> WHERE id> 100 LIMIT 10;
mysql> SELECT FOUND_ROWS ();
This is especially useful if you use an ORDER BY clause, or a complex consultation with subqueries, multiple JOIN or many calculations.
Check MySQL Manual
Thursday, October 25, 2007
Autoloading classes
Since PHP 5, it is not necessary to load all classes at the beginning of each script, but if there is a function __autoload is called when they want to use a class that does not exist. This function takes the name of the class you want and it must bear responsibility for making that class exist, in order to avoid the throwing an error because it does not exist.
This is a good step forward for PHP 5, which since version 5.1.2 also gives us the possibility to register multiple functions to do this, rather than simply just one as was previously, through spl_autoload_register.
This is a good step forward for PHP 5, which since version 5.1.2 also gives us the possibility to register multiple functions to do this, rather than simply just one as was previously, through spl_autoload_register.
Thursday, October 18, 2007
Switch with expressions
The switch usually are very useful, but also very limited. Looking the way, we can extend its use to evaluate expressions, and call functions. What we have to do is put expressions in the case to be an argument to compare.
For example, we can do the following
Thus, instead of using three chained IFs, we can resort to this option, so that our code is more readable.
For example, we can do the following
switch (true) {
case ($variable >= 0 && $variable < 3):
echo '$variable está entre 0 y 3';
break;
case ($variable >= 3 && $variable < 7):
echo '$variable está entre 3 y 7';
break;
case ($variable >= 7):
echo '$variable es mayor a 7';
break;
}
Thus, instead of using three chained IFs, we can resort to this option, so that our code is more readable.
Tuesday, October 16, 2007
Single and double quoted
For most people, the single and doubles quotes in PHP are equal. But fundamental differences exists. Using double quotes there are more special characters: \n \r \t \\ \$ \" \[0-7] (1,3) \x [0-9A-Fa-f] (1,2) while with single quotes we only have \\ \'.
Knowing this already, we can assume that the single quotes are faster. On the other hand, we must add that within the double quotes variables may be used without concatenate, but writing it directly on the string contents.
More information can be found in the PHP manual, in String section.
Finally, let's compare the times of each, in various circumstances.
View example
Knowing this already, we can assume that the single quotes are faster. On the other hand, we must add that within the double quotes variables may be used without concatenate, but writing it directly on the string contents.
More information can be found in the PHP manual, in String section.
Finally, let's compare the times of each, in various circumstances.
View example
Thursday, October 11, 2007
Handling dates
It is normal to have to change the format of a date to suit one type of database, or to be presented to a user. Usually, strtotime is a good tool to do so because it supports the traditional format of MySQL and many others, but the problem is usually when we get a date format dd/ mm/yy, because by default this feature takes American format mm/dd/yy and can be confused with the 01/07 January 7, instead of July 1 that we expected. The solution offered by PHP is the function strptime, which allows us to indicate the format of the date. However, this feature is quite new (since PHP 5.1.0) and is not implemented on Windows, which is quite limited. Therefore, we can create a small function, for this purpose.
function strtotime2($date)
{
if (preg_match('#^((0?[1-9])|([1-2]?[0-9])|(3[0-1]))/(0?[1-9]|(1[0-2]))/((19|20)?([0-9]{2}))$#', $date))
{
list($day, $month, $year) = explode('/', $date);
return mktime(0, 0, 0, $month, $day, $year);
} else
{
return strtotime($date);
}
}
function strtotime2($date)
{
if (preg_match('#^((0?[1-9])|([1-2]?[0-9])|(3[0-1]))/(0?[1-9]|(1[0-2]))/((19|20)?([0-9]{2}))$#', $date))
{
list($day, $month, $year) = explode('/', $date);
return mktime(0, 0, 0, $month, $day, $year);
} else
{
return strtotime($date);
}
}
Thursday, October 4, 2007
Flexible parameters, hard returns
When programming a function, or a method of a class, always is the best thing to be able to receive any type of parameter. Analyze if is more comfortable to mix two parameters in one, using an Array, or if a data can be of several types. All these things it is necessary to have them in account so that soon it is less difficult to work with which already it is done. Another thing that we must try is always to return the same data type, even if it were not possible to be made what it was expected, then if an Array is due to return, but was an error we can return an empty Array instead of false or null. A simple example of this
function select($nombre, $valores = array(), $seleccionado = '', $atributos = array())
{
if (!is_array($valores) || count($valores) == 0)
{
return '';
}
if (is_string($nombre))
{
if (is_array($atributos))
{
$atributos['name'] = $nombre;
} else
{
$atributos .= ' name="' . htmlentities($nombre) . '"';
}
}
$out = '<select';
if (is_array($atributos))
{
foreach ($atributos as $atributo_nombre => $atributo_valor)
{
$out .= ' ' . $atributo_nombre . '="' . htmlentities($atributo_valor) . '"';
}
} else
{
$out .= ' ' . $atributos;
}
$out .= '>';
foreach ((array)$valores as $valor_clave => $valor_etiqueta)
{
$out .= '<option value="' . htmlentities($valor_clave) . '"' . ($valor_clave == $seleccionado || (is_array($seleccionado) && in_array($valor_clave,$seleccionado)) ? 'selected="selected"' : '') . '>' . htmlentities($valor_etiqueta) . '</option>';
}
return $out . '</select>';
}
echo select('select',array('a' => 'A', 'b' => 'B','c' => 'C','d' => 'D'),array('a'),array('id' => 'select', 'multiple' => 'multiple'));
echo PHP_EOL;
echo select('select',array('a' => 'A', 'b' => 'B','c' => 'C','d' => 'D'),'a','id="select"');
echo PHP_EOL;
echo select('select');
Sunday, September 30, 2007
Form processing
Always, the greater problem, is to process sent data. We are going to make a pursuit of which things are necessary to review for each form. As a previous notion, we must consider that all the data that client sends (POST, GET, COOKIE) is unreliable.
- Review the permission of the user
All the users do not have permissions for all the forms, that is clear. It is necessary to establish if the user can send that form or no, or if only he can do it partly. - Validate all the data
It means that by each form, it is necessary to establish conditions. In general, the text fields must have a maximum length (normal it is to establish it according to the data base) or fixed (for example, the credit cards codes). Also it is necessary to review the format (usually for the email directions). There are data that only can be numerical, or dates that can not be valid.
Checkbox, radio buttons and dropdowns have a range of prefixed options and they are not possible to left it.
All these things it is necessary to have them in account, because an erroneous data can cause that information lost, but can be avoided if him force to the user to correct that error. - Save data
Depending the destiny on the entered data, it is necessary to save the data of the form that corresponds. In general, we are going to keep them in databases, reason why the functions *_escape_string provide a form easy to escape the data according to the type of database that we use.
In this point, it is necessary to have well-taken care of with the “magic quotes” (magic_quotes_gpc), that if they are enabled can cause the data doubly escaped. The best thing is to clear the quotes, if this config is in On.
So why don't we forget to escape data, if we have magic_quotes_gpc?
The idea of magic_quotes was not to have to escape data, and to facilitate the task to the programmer. The problem of this function, is that it escapes data in an arbitrate way and without considering in where they are used such.
Another possible error is to want to keep data that the user did not submit, but to have magic_quotes_gpc On we did not escape, incorrectly. - Save the results
The data are valid, and prepared… The only thing that is is to save it, and to make any other process that is necessary. - Show the results
Still our work did not finish. The information that we kept, probably we want it to show somebody. In this point it is very important to escape the data again. Previously we kept it as the user submitted it, but at the time of showing it in a page, it is necessary to avoid malisiosa information. In general, to escape HTML entities is enough for this, but it would be better to escape all the entities, “even more rare” to display the information correctly.
Tuesday, September 25, 2007
Conexión por IP
Recently I discovered that is faster to connect to a server used its IP that its name. For example, instead of mysql_connect(“localhost”); one can use mysql_connect(“127.0.0.1”); and it ends up improving the speed of connection. A small optimization, but frequent.
Sunday, September 23, 2007
Storing array elements in a variable
The other day, called the attention to read that is slower to accede to an array element than to a variable. I decided to prove whatever is the difference, and if it is worth the trouble. My conclusion is that the difference exists and if is called more than 10 times to the same index, can be worth the trouble to create a variable for that, but is also only recommendable to do it within a function, in a “scope” so that it is not all along in the memory.
View example
View example
Thursday, September 20, 2007
Reading the manual
I must read the manual
I must read the manual
I must read the manual
I must read the manual
Yeah, it is boring, but it is necessary to consider that PHP has many functions that one perhaps ignores and we can avoid us to rediscover the wheel.
Also it is necessary to read the commentaries of the users, many holes are covered there.
The last function I discover: dl
I must read the manual
I must read the manual
I must read the manual
Yeah, it is boring, but it is necessary to consider that PHP has many functions that one perhaps ignores and we can avoid us to rediscover the wheel.
Also it is necessary to read the commentaries of the users, many holes are covered there.
The last function I discover: dl
Sunday, September 16, 2007
Iterate over array
Perhaps it sounds repeated to the for - while post, but now instead of executing a code N times, I want to run all the positions of an array. Which is the most advisable way?
In the first place, we have the optimized for.
On the other hand, we can use foreach, that exactly crosses the array of data.
A last alternative is to be crossing the array using its internal pointer.
In this case, the best alternative is foreach, specially dedicated for this.
View example
In the first place, we have the optimized for.
On the other hand, we can use foreach, that exactly crosses the array of data.
A last alternative is to be crossing the array using its internal pointer.
In this case, the best alternative is foreach, specially dedicated for this.
View example
Thursday, September 13, 2007
Post or Get
Which is the criteria to choose if a form must go by Post or Get?
W3c gives us a list to decide. We are going to use that list as it bases, and to try to extend it a bit
GET
* W3C: The interaction is more like a question (?)
* It is a data that is used as guide for the presentation
* It is wanted to be able to offer the possibility of copying and pasting to keep it, enter it in a page, to pass it to it to another person
POST
* W3C: The interaction is more like an order
* W3C: The interaction changes the state of the resource in a way that the user would perceive
* W3C: The user be held accountable for the results of the interaction
* Rebound second of the W3C like very important: to try to maintain the processings of forms like Post
* It handles “sensible” data like passwords
* The information is much (the amount of characters of URI can be limited pro the servant)
BOTH
* When data are processed, it is moral convention to make Post/Redirect/Get
W3c gives us a list to decide. We are going to use that list as it bases, and to try to extend it a bit
GET
* W3C: The interaction is more like a question (?)
* It is a data that is used as guide for the presentation
* It is wanted to be able to offer the possibility of copying and pasting to keep it, enter it in a page, to pass it to it to another person
POST
* W3C: The interaction is more like an order
* W3C: The interaction changes the state of the resource in a way that the user would perceive
* W3C: The user be held accountable for the results of the interaction
* Rebound second of the W3C like very important: to try to maintain the processings of forms like Post
* It handles “sensible” data like passwords
* The information is much (the amount of characters of URI can be limited pro the servant)
BOTH
* When data are processed, it is moral convention to make Post/Redirect/Get
Tuesday, September 11, 2007
Error reporting
One does not program correctly, if errors exist. And if these errors escape of our sight, it will be more difficult to detect them and to correct them. An error that does not cause negative consequences, continues being an error. Commonest, in this sense, it is to verify the value of variables that are not initialized, or we do not know if they are it… If we proved the difference between
1) if ($variable)
2) if (isset ($variable))
3) if (! empty ($variable))
The first that calls to me attention is the more slow is the first option, if the variable is not defined, but is variable is defined is the more fast that empty and that isset, with which if he is sure that the variable exists, this is the best solution, but before the doubt he is preferable to use empty/isset.
Returning to the subject of the errors, whenever it is codified is good for seeing the errors, therefore always it is good for executing
error_reporting (E_ALL);
while it is being developed, and to reduce the level to E_NONE when he is in a site live, or to eliminate error_display
View example
1) if ($variable)
2) if (isset ($variable))
3) if (! empty ($variable))
The first that calls to me attention is the more slow is the first option, if the variable is not defined, but is variable is defined is the more fast that empty and that isset, with which if he is sure that the variable exists, this is the best solution, but before the doubt he is preferable to use empty/isset.
Returning to the subject of the errors, whenever it is codified is good for seeing the errors, therefore always it is good for executing
error_reporting (E_ALL);
while it is being developed, and to reduce the level to E_NONE when he is in a site live, or to eliminate error_display
View example
Sunday, September 9, 2007
Listing directories
The necessity to look for all the archives in a folder is common. The common way is to use opendir, but the function glob approaches to us alongside dark side of the force, offering us a simpler alternative… Nevertheless, this solution is slower.
Another alternative is the function to dir, that returns a directory object, a more “elegant” solution if it is wanted, but is not more than wrapper of the same, reason why it is not faster.
View example
Another alternative is the function to dir, that returns a directory object, a more “elegant” solution if it is wanted, but is not more than wrapper of the same, reason why it is not faster.
View example
Saturday, September 8, 2007
Avoid double functions calls
I was thinking that I can take any function and optimize it by storing results already calculated in a temporary variable.
Therefore, I took common mathematical formula, the “quadratic one” that is used to obtain the roots of a polynomial of degree two, and began to prove forms to improve it.
Several were the attempts, and the conclusion at which I arrived is that although he is better to store results of calls of functions, is not the best thing to keep it from operating simpler like the multiplication.
View example
Therefore, I took common mathematical formula, the “quadratic one” that is used to obtain the roots of a polynomial of degree two, and began to prove forms to improve it.
Several were the attempts, and the conclusion at which I arrived is that although he is better to store results of calls of functions, is not the best thing to keep it from operating simpler like the multiplication.
View example
Pair or odd
How can we know if an integer number is pair or odd?
Of course, it is not too hard.
When I was just starting, I remembered I have looked for a way to do this, not too practical
floor($a / 2) == $a / 2;
The result is correct, but it can be much easier knowing the % operator
$a % 2 == 0;
However, you can still do it faster, but not necessarily easier, checking if the binary contains the 1 or not.
$a & 1 == 0
View example
Of course, it is not too hard.
When I was just starting, I remembered I have looked for a way to do this, not too practical
floor($a / 2) == $a / 2;
The result is correct, but it can be much easier knowing the % operator
$a % 2 == 0;
However, you can still do it faster, but not necessarily easier, checking if the binary contains the 1 or not.
$a & 1 == 0
View example
str_replace - strtr
This two functions are too similar. Usually, str_replace is more famous, but which one is better? Let's try...
str_replace('e','a','hello world');
strtr('hello world','e','a');
Let's compare a simple replace. In this comparison, str_replace takes a point.
What happens if it is wanted to replace a text that is not?
Both functions are quicker, but str_replace still more optimal. At this instance, it seems this options is better, but both functions allows multiple replacements at a time. Let's try it.
str_replace(array('o','e'),'a','hello world');
strtr('hello world',array('o' => 'a','e' => 'a'));
Here we reeplace "o" and "e" for "a", and str_replace still likes better... Let's give strtr a las chance
str_replace(array('o','e'),array('i','o'),'hello world');
strtr('hello world',array('o' => 'i','e' => 'o'));
In this case, the replacements are 'o' for 'i', and 'e' for 'a', and surprisely strtr takes the victory.
Conclusion: usually, its preferable to use str_replace, but when you want to replace many characters for many others characters (and not only a value) strtr is better.
View example
str_replace('e','a','hello world');
strtr('hello world','e','a');
Let's compare a simple replace. In this comparison, str_replace takes a point.
What happens if it is wanted to replace a text that is not?
Both functions are quicker, but str_replace still more optimal. At this instance, it seems this options is better, but both functions allows multiple replacements at a time. Let's try it.
str_replace(array('o','e'),'a','hello world');
strtr('hello world',array('o' => 'a','e' => 'a'));
Here we reeplace "o" and "e" for "a", and str_replace still likes better... Let's give strtr a las chance
str_replace(array('o','e'),array('i','o'),'hello world');
strtr('hello world',array('o' => 'i','e' => 'o'));
In this case, the replacements are 'o' for 'i', and 'e' for 'a', and surprisely strtr takes the victory.
Conclusion: usually, its preferable to use str_replace, but when you want to replace many characters for many others characters (and not only a value) strtr is better.
View example
Naming variables
It is important that our code can be read, by ourself or by others, so it is very likely to name of our vars explain what they contain.
Personally, I don't like to include the data type in the variable name, but what it mean.
As an usual exception to this rule you have the variables with no real sense, but useful, for example
for ($i = 0; $i < N; $i++) {
for ($j = 0; $j < M; $j++) {
}
}
Personally, I don't like to include the data type in the variable name, but what it mean.
As an usual exception to this rule you have the variables with no real sense, but useful, for example
for ($i = 0; $i < N; $i++) {
for ($j = 0; $j < M; $j++) {
}
}
for - while
Usually, to iterate a code N times you do
for ($a = 0; $a < N; $a++) {
but, thinking a bit, this code can be optimized, because the second and third sentence can be joined, so we get this
for ($a = -1; ++$a < N;) {
Also, you can think it in this way
$a = 0;
while (++$a < N) {
but the previous approach seems (a bit) better, in the practice. This optimization can improve not much your code, we have to keep in mind this is one of the most common iterations, and you can repeat it a lot along your work.
View example
for ($a = 0; $a < N; $a++) {
but, thinking a bit, this code can be optimized, because the second and third sentence can be joined, so we get this
for ($a = -1; ++$a < N;) {
Also, you can think it in this way
$a = 0;
while (++$a < N) {
but the previous approach seems (a bit) better, in the practice. This optimization can improve not much your code, we have to keep in mind this is one of the most common iterations, and you can repeat it a lot along your work.
View example
Subscribe to:
Posts (Atom)