Last Updated:

PHP Fundamentals

Cycles. FOR loop

 

These are the most difficult loops in PHP. They resemble the corresponding C cycles.

structure:

for (expression1; expression2; expression3) {block_execution}

or

for (expression1; expression2; expression3): endfor execution block;

Here, as we see, the condition consists of three expressions at once. The first expression1 is calculated unconditionally once at the beginning of the cycle. At the beginning of each iteration, the expression2 is calculated. If it is True, then the loop lasts and all runtime_block commands are executed. If the expression2 is calculated as False, then the loop stops. At the end of each iteration (that is, after executing all the commands of the execution_block), the expression3 is calculated.

Each of the expressions 1, 2, 3 may be empty. If the expression2 is empty, then this means that the loop must be executed indefinitely (in this case, PHP considers this expression always true). This is not as useless as it seems, because the loop can be stopped using the break operator .

For example, all even numbers can be derived using the for loop as follows:

If you omit the second expression (the condition $ i <10), then the same problem can be solved by stopping the cycle with the break operator .

= 10) break; If $ i is greater than or equal to 10, // then we stop the if loop ($ i% 2 == 0) print $ i; If the number is even, // then we print it}?>

You can omit all three expressions. In this case, the initial value of the $ i counter will simply not be set and it will not change every time at the end of the cycle. All these actions can be written as separate commands either in the field_block or before the cycle:

= 10) break; If $ i is greater than or equal to 10, // then we stop the if loop ($ i% 2 == 0) print $ i; If the number is even, // then we print it $ i ++; We increase the counter by one}?>

In the third expression of the for construct, you can write several simple commands through a comma at once. For example, if we want to simply display all the numbers, then the program can be written quite simply:

CYCLE WHILE

 

While

structure:

while {run_block}

or

while( expression): endwhile execution block;

while - Simple cycle. It instructs PHP to execute block_execution commands as long as the expression is evaluated as True (here, as in if , the expression is reduced to a logical type). The value of the expression is checked every time at the beginning of the loop, so that even if its value has changed during the execution of the run_block, the loop will not be stopped until the end of the iteration (that is, until all run-time block commands are executed).

Example 3.5. while operator

 

PHP Fundamentals. Cycles. Cycle DO ... WHILE

Do ... while

cycles do.. while very similar to while loops , with the only difference being that the truth of the expression is checked at the end of the loop and not at the beginning. Thanks to this, the block_execution of the cycle do ... while guaranteed to be performed at least once.

structure:

do {block_execution} while (expression);

Example 3.6. operator do.. while

Foreach

 

Another useful design. It appeared only in PHP4 and is designed exclusively for working with arrays.

syntax:

foreach ($ array as $ value) {block_execution}

or

foreach ($ array as $ key => $ value) {run_block}

In the first case, a loop is formed for all elements of the array specified by the $ array variable. At each step of the loop, the value of the current element of the array is written to the $ value variable, and the internal counter of the array moves by one (so that the next step will be visible the next element of the array). Inside the execution_block, the value of the current element of the array can be obtained using the $ value variable. Execution of the execution_block occurs as many times as the elements in the $ array.

The second form of the record, in addition to the above, at each step of the loop writes the key of the current element of the array to the $ key variable, which can also be used in the field_block.

when foreach starts execution, the internal index of the array is automatically set to the first element.

$ val) {// in addition to the greeting, // display the numbers in the list, that is, the echo keys "Hello, $ val! Are you on the list under the number $ k "; }? >

Example 3.7. foreach operator

Operators. Break operator. Infinite cycles

Sometimes you need to immediately complete the work of a cycle or its individual iteration. To do this, use the operators break andcontinue .

Break

the break operator ends the execution of the current loop, be it for , foreach , while , do.. while or switch . break can be used with a numerical argument that says how many control structures containing it must be completed.

Example 3.8. break operator

The result of this script will be approximately the following:

1:7 The cycle works 2:2 The cycle works 3:5 Number of iterations of the cycle 3

If you specify a number after the break operator, then this number of loops containing this operator will be interrupted. In the example above, this is irrelevant because there are no nested cycles. Let's change our script a bit:

Exit from switch (n = $ n) "; break 1; Stop the switch // (the first contains a break loop) case 10: echo " Exit from switch and while (n = $ n) "; break 2; Stop switch and while // (two contain break loops) default: echo "switch works (n = $ n),";} echo "while works - step $ i "; $ i ++;} echo " The number of iterations of the loop $ i ";? >

Sometimes it is necessary not to completely stop the work of the cycle, but only to begin its new iteration. the continue operator allows you to assume further instructions from the execution_block of any cycle and continue execution from a new circle. continuecan be used with a numerical argument that indicates how many control constructs containing it should complete the work.

In the example of the previous paragraph, replace the break operator with continue . In addition, we will limit the number of steps of the cycle to three.

The result of this script will be

1:10 Cycle works 2:5 New iteration 2:1 Cycle works 3:1 Cycle works 4:1 Cycle works Number of iterations of cycle 4

Note that after performing the continue operator, the cycle does not end there. In the example, the cycle counter does not change when the number 5 is obtained, since it is after the continue operator . In fact, with the help of continue, we try to avoid a situation where the number 5 will be generated. Therefore, it was possible to simply write by replacing thecontinue operator to check the truth of the expression:

In PHP, there is one feature of using the continue operator - In switch designs, it works in the same way asbreak . if the switch is inside the loop and you need to start a new iteration of the cycle, you should use continue 2.

Operators. Bit operators

 

Bitwise operators allow you to read and set specific bits of integers.

Bitwise operators
exampleNameoutcome
 $ A & $ b Installed only those bits that are set in $ a, and in $ b.
 $ A | $ borThose bits that are set to $ a or $ b are installed.
 $ A ^ $ bWhich excludes orInstalled only those bits that are set either only in $ a, or only in $ b, but not in both at the same time.
 ~ $ AObjectionsThose bits that are not set to $ a are installed, and vice versa.
 $ A « $ bShift leftAll bits of the $ a variable are shifted by $ b positions to the left (each position implies "multiplication by 2")
 $ A » $ bShift to the rightAll bits of the $ a variable are shifted by $ b positions to the right (each position implies a "division by 2")

Bitwise shift in PHP is an arithmetic operation. Bits shifted abroad numbers are discarded. Shifting to the left complements the number with zeros to the right, while shifting the iconic bit of the number to the left, which means that the operand sign is not saved. Shifting to the right preserves a copy of the shifted sign bit on the left, which means that the operand sign is preserved.

Use parentheses to ensure the required priority of operators. For example, $ a & $ b == truesnachala checks for equality, and then executes bitwise and; whereas ($ a & $ b) == true first performs bitwise and then performs an equality check.

Don't forget about converting data types. If both the left and right operands are strings, the bitwise operator will work with the ASCII character values of those strings.

THE PHP settings option error_reporting uses bitwise values,

providing a real demonstration of extinguishing bit values.

To show all errors except comments,

instructions in the php file.ini suggest using:

E_ALL & ~ E_NOTICE

We start with the value of E_ALL:

Then we take the value of E_NOTICE ...

... And invert it with ~:

Finally, use bitwise AND (&) to install only those bits,

which are set to one in both values:

Another way to achieve this is to use excludes Or (XOR, ^),

to get only those bits that are set to one

either only in one, or only in another sense:

E_ALL ^ ?? E_NOTICE

The error_reporting option can also be used for demonstration

bit installations. You can show only errors and processed errors

As follows:

E_ERROR | E_RECOVERABLE_ERROR

Here we combine E_ERROR

using the operator OR (OR, |),

Mathematical functions

 

  • abs - Number module
  • acos - arccosinus
  • acosh - Hyperbolic Arccosine
  • asin - Arcsine
  • asinh - Hyperbolic Arcsine
  • atan2 - Arctangent of two variables
  • atan - Arctangent
  • atanh - Hyperbolic Arctangent
  • base_convert - Convert a number between arbitrary number systems
  • bindec - Binary to Decimal
  • ceil - Rounds the fraction up
  • cos - Cosine
  • cosh - Hyperbolic cosine
  • decbin - Translates a number from decimal to binary
  • dechex - Translates a number from decimal to hexadecimal
  • decoct - Translates a number from decimal to octal
  • deg2rad - Converts values from degrees to radians
  • exp - Calculates the number e to the power
  • expm1 - Returns exp (number) - 1, calculated in such a way that the result is accurate, even if the number is close to zero.
  • floor - Rounds the fraction down
  • fmod - Returns the fractional remainder of modulo division
  • getrandmax - the maximum possible random number is increased
  • hexdec - Translates a number from a hexadecimal number system to decimal
  • hypot - Calculates the length of the hypotenuse of a right triangle
  • is_finite - Checks whether a value is a valid end number
  • is_infinite - Checks if the value is infinite
  • is_nan - Checks if the value is "not a number"
  • lcg_value – Combined linearly congruent generator
  • log10 - Decimal Logarithm
  • log1p - Returns a log (1 + number) calculated so that the result is accurate, even if the value of number is close to zero
  • log - Natural logarithm
  • max - Returns the largest value
  • min - Finds the smallest value
  • mt_getrandmax - Shows the maximum possible value of a random number
  • mt_rand - Generates a random value using the mt method
  • mt_srand - Re-initializes the random number generator mt
  • octdec - Translates a number from octal number system to decimal
  • pi - Returns the number pi
  • pow - Exponentiation
  • rad2deg - Converts values from radians to degrees
  • rand - Generates a random number
  • round - Rounds a float number
  • sin - sinus
  • sinh - Hyperbolic sinus
  • sqrt - Square root
  • srand - Changes the initial number of the pseudo-random number generator
  • tan - Tangent
  • tanh - Hyperbolic tangent

 

Operators. Operator priority

 

The priority of the operator determines how "closely" it relates the two expressions. For example, the expression 1 + 5 * 3 is calculated as 16, not 18, because the multiplication operator ("*") has a higher priority than the append operator ("+"). Parentheses can be used to force an indication of the order in which operators are executed. For example, the expression (1 + 5) * 3 is calculated as 18.

If operators have equal priority, then whether they will be executed from right to left or from left to right is determined by their associativity - see examples below.

The following table lists operators sorted by decreasing their priorities. Operators placed on the same line have the same priority and the order of their execution is determined based on their associativity.

The order of execution of operators
AssociativityoperatorAdditional Information
Non-associative clone newclone and new
Left[ array ()
rights ++ - ~ (Int) (float) (string) (array) (object) (bool) @types and increment / decrement
Non-associative instanceofTypes
rights!Logical operators
Left * /%Arithmetic operators
Left + -.Arithmetic operators and string operators
Left << »Bitwise operators
Non-associative <<=>> =Comparison operators
Non-associative ==! = ===! ==Comparison operators
Left&bitwise operators and links
Left^Bitwise operators
Left|Bitwise operators
Left &&Logical operators
Left ||Logical operators
Left ? :Ternary operator
rights = + = - = * = / =. =% = & = | = ^ = « = » = =>Assignment operators
Left andLogical operators
Left xorLogical operators
Left orLogical operators
Left,Many uses

For operators with equal priority, the left associativity implies that the expression is calculated from left to right, the right associativity, respectively, implies the opposite order. Non-associative operators with equal priority cannot be combined with themselves. For example, expression 1 <2> 1 in PHP is invalid, while expression 1 <= 1 == 1 is correct because the operator T_IS_EQUAL has a lower priority than the T_IS_SMALLER_OR_EQUAL statement.

Example #1 Associativity

$ A = 3 * 3% 5; (3 * 3)% 5 = 4
$ A = true? 0: true? 1: 2; (True? 0: true)? 1: 2 = 2

$ A = 1;
$ B = 2;
$ A = $ b + = 3; $ A = ($ b + = 3) -> $ a = 5, $ b = 5

When sharing ++ and + the result will be undefined
$ A = 1;
echo ++ $ a + $ a ++; Can deduce 4 or 5
?>

The use of parentheses, even where there is no strict need for them, usually significantly improves the readability of the code.

Remarks:

Despite the fact that the = operator has a lower priority than most other operators, PHP still allows the following construct: if (! $ A = foo ()), which assigns the variable $ a the result of the execution of the function foo ().

Operators. String operators

In PHP, there are two operators for working with strings (strings). The first is the concatenation operator ('.'), Which returns a string representing the connection of the left and right arguments. The second is the assignment operator with concatenation ('. ='), which attaches the right argument to the left. For more complete information, see assignment operators.

$ A = "Hello";
$ B = $ a. "World!"; $B now contains the line "Hello World!"

$ A = "Hello";
$ A. = "World!"; $A now contains the line "Hello World!"
?>

Namedescription
 addcslashesScreens special characters in the style of the C language
 addslashesScreens special characters in a row
 bin2hexConverts binary data into a hexadecimal representation
 chrReturns a character by its code
 chunk_splitBreaks a line into slices
 convert_cyr_stringConverts a string from one Cyrillic to another
 count_charsReturns information about the characters included in the string
 crc32Calculates CRC32 for a row
 cryptIrreversible encryption (hashing)
 echoOutputs one or more rows
 explodeBreaks a line into a substring
 fprintfЗаписує отформатированную string в поток
 get_html_translation_tableReturns the conversion table used by the htmlspecialchars () and htmlentities () functions
 hebrevConverts Hebrew text from logical to visual coding.
 hebrevcConverts Hebrew text from logical to visual encoding with converting line translation.
 htmlentitiesConverts characters to the corresponding HTML essence.
 htmlspecialcharsConverts special characters to HTML essence
 html_entity_decodeConverts HTML entities to the appropriate characters
 implodeJoins array elements into a string
 localeconvReturns information about number formats
 ltrimRemoves spaces from the beginning of a line
 md5Returns the MD5 hash of a string
 md5_fileReturns the MD5 hash of a file
 metaphoneReturns the metaphone key for a string
 nl2brInserts HTML line break code before each line is translated
 number_formatFormats a number by splitting groups
 ordReturns the ASCII code of a character
 parse_strParses a string into variables
 printdisplays a string
 printfDisplays an formatted string
 quoted_printable_decodeDecodes string encoded by quoted printable method
 quotemetaEscapes special characters
 rtrimRemoves spaces from the end of a line
 sha1Returns the SHA1 hash of a string
 sha1_fileReturns the SHA1 hash of a file
 similar_textCalculates the degree of similarity between two rows
 soundexReturns the soundex key for a string
 sprintfReturns отформатированную рядок
 sscanfParses a string according to a given format
 strcasecmpCase-insensitive string comparison, safe for binary data
 strcmpRow comparison that is safe for binary data
 strcollCompare strings based on current locale
 strcspnReturns the length of the area at the beginning of the row that corresponds to the mask
 stripcslashesRemoves character shielding produced by the addcslashes () function
 striposReturns the position of the first occurrence of a substring, case-sensitive
 stripslashesRemoves character shielding produced by the addslashes () function
 strip_tagsRemoves HTML and PHP tags from a string
 stristrAnalogous to the strstr function, but case-independent.
 strlenReturns the length of a string
 strnatcasecmpCase-insensitive string comparison using the "natural ordering" algorithm
 strnatcmpComparison of strings using the "natural ordering" algorithm
 strncasecmpComparison of the first n characters of strings excluding case, safe for data in binary form
 strncmpComparison of the first n characters of strings excluding case, safe for data in binary form
 strposFinds the first occurrence of a substring in a row
 strrchrFinds the last occurrence of a character in a string
 strrevFlips a line
 strriposReturns the position of the last occurrence of a substring, case-sensitive
 strrposFinds the last occurrence of a character in a string
 strspnReturns the length of an area at the beginning of a row corresponding to a mask
 strstrFinds the first occurrence of the substring
 strtokbreaks a line
 strtolowerConverts a string to lowercase
 strtoupperConverts a string to uppercase
 strtrConverts specified characters
 str_ireplaceFor a register-dependent independent version of the function str_replace ().
 str_padComplements the string with another line to the specified length
 str_repeatReturns a repeating row
 str_replaceReplaces the search bar with a replacement string
 str_rot13Performs ROT13 over-line conversion
 str_shuffleRearranges characters in a string
 str_splitConverts a string to an array
 str_word_countReturns information about words that are included in a string
 substrThe function returns part of a row
 substr_countCounts the number of occurrences of a substring in a string
 substr_replaceReplaces part of a row
 trimRemoves spaces from the beginning and end of a line
 ucfirstConverts the first character of a string to uppercase
 ucwordsConverts to uppercase the first character of each word in a string
 vprintfDisplays an formatted string
 vsprintfReturns отформатированную рядок
 wordwrapPerforms line wrapping by a given number of characters using a line break character.

Switch operator

 

Another design that allows you to check the condition and perform various actions depending on this is a switch. In Russian, the name of this operator can be translated as "switch". And his meaning is just that. Depending on what value the variable has, it switches between different blocks of action. switch is very similar to the if ... elseif... Else or a set of if statements . The switch structure can be written as follows:

switch (expression or variable) {case value1: block_action1break; case value2: block_action2break; ... default: block_action_by_umolchaniya}

Unlike if , here the value of the expression is not given to a logical type, but is simply compared with the values listed after the keywords case (Value1, Value2, etc.). If the value of the expression coincided with any variant, then the corresponding block_of_actions is performed - from the colon after the matching value to the end of the switch or to the first operator break , if one is found. If the value of the expression does not coincide with any of the options, then the default actions (action_block_by_umolchaniya) are performed that are after the keyword default. the expression in switch is calculated only once, and in the elseif statement - each time, so if the expression is complex enough, then the switch works faster.

Example 3.3 can be rewritten using switch as follows:

If in this example we omit the break operator , for example, in the case "Peter" :, then if the variable turns out to be equal to the line "Peter", after displaying the message "Hello, Petya!" the program will go further and display the message "Hello, Senya!" and only then, having met break , continue its execution outside the switch .

for the switch construct , As with if , an alternative syntax is possible, where the aligned bracket that opens the switch is replaced by a colon, and closes - endswitch; Under.