PHP – Conditional Operators

PHP – Conditional Operators Examples ”; Previous Next You would use conditional operators in PHP when there is a need to set a value depending on conditions. It is also known as ternary operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. Ternary operators offer a concise way to write conditional expressions. They consist of three parts: the condition, the value to be returned if the condition evaluates to true, and the value to be returned if the condition evaluates to false. Operator Description Example ? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y Syntax The syntax is as follows − condition ? value_if_true : value_if_false Ternary operators are especially useful for shortening if-else statements into a single line. You can use a ternary operator to assign different values to a variable based on a condition without needing multiple lines of code. It can improve the readability of the code. However, you should use ternary operators judiciously, else you will end up making the code too complex for others to understand. Example Try the following example to understand how the conditional operator works in PHP. Copy and paste the following PHP program in test.php file and keep it in your PHP Server”s document root and browse it using any browser. <?php $a = 10; $b = 20; /* If condition is true then assign a to result otheriwse b */ $result = ($a > $b ) ? $a :$b; echo “TEST1 : Value of result is $result n”; /* If condition is true then assign a to result otheriwse b */ $result = ($a < $b ) ? $a :$b; echo “TEST2 : Value of result is $result”; ?> It will produce the following output − TEST1 : Value of result is 20 TEST2 : Value of result is 10 Print Page Previous Next Advertisements ”;

PHP – For Loop

PHP – For Loop ”; Previous Next A program by default follows a sequential execution of statements. If the program flow is directed towards any of earlier statements in the program, it constitutes a loop. The for statement in PHP is a convenient tool to constitute a loop in a PHP script. In this chapter, we will discuss PHP’s for statement. Flowchart of “for” Loop The following flowchart explains how a for loop works − The for statement is used when you know how many times you want to execute a statement or a block of statements. Syntax of “for” Loop The syntax of for statement in PHP is similar to the for statement in C language. for (expr1; expr2; expr3){ code to be executed; } The for keyword is followed by a parenthesis containing three expressions separated by a semicolon. Each of them may be empty or may contain multiple expressions separated by commas. The parenthesis is followed by one or more statements put inside curly brackets. It forms the body of the loop. The first expression in the parenthesis is executed only at the start of the loop. It generally acts as the initializer used to set the start value for the counter of the number of loop iterations. In the beginning of each iteration, expr2 is evaluated. If it evaluates to true, the loop continues and the statements in the body block are executed. If it evaluates to false, the execution of the loop ends. Generally, the expr2 specifies the final value of the counter. The expr3 is executed at the end of each iteration. In most cases, this expression increments the counter variable. Example The most general example of a for loop is as follows − <?php for ($i=1; $i<=10; $i++){ echo “Iteration No: $i n”; } ?> Here is its output − Iteration No: 1 Iteration No: 2 Iteration No: 3 Iteration No: 4 Iteration No: 5 Iteration No: 6 Iteration No: 7 Iteration No: 8 Iteration No: 9 Iteration No: 10 An infinite “for” loop Note that all the three expressions in the parenthesis are optional. A for statement with only two semicolons constitutes an infinite loop. for (; 😉 { Loop body } To stop the infinite iteration, you need to use a break statement inside the body of the loop. A decrementing “for” loop You can also form a decrementing for loop. To have a for loop that goes from 10 to 1, initialize the looping variable with 10, the expression in the middle that is evaluated at the beginning of each iteration checks whether it is greater than 1. The last expression to be executed at the end of each iteration should decrement it by 1. <?php for ($i=10; $i>=1; $i–){ echo “Iteration No: $i n”; } ?> It will produce the following output − Iteration No: 10 Iteration No: 9 Iteration No: 8 Iteration No: 7 Iteration No: 6 Iteration No: 5 Iteration No: 4 Iteration No: 3 Iteration No: 2 Iteration No: 1 Using the “for…endfor” construct You can also use the “:” (colon) symbol to start the looping block and put endfor statement at the end of the block. <?php for ($i=1; $i<=10; $i++): echo “Iteration No: $i n”; endfor; ?> Iterating an indexed array using “for” loop Each element in the array is identified by an incrementing index starting with “0”. If an array of 5 elements is present, its lower bound is 0 and is upper bound is 4 (size of array -1). To obtain the number of elements in an array, there is a count() function. Hence, we can iterate over an indexed array by using the following for statement − <?php $numbers = array(10, 20, 30, 40, 50); for ($i=0; $i<count($numbers); $i++){ echo “numbers[$i] = $numbers[$i] n”; } ?> It will produce the following output − numbers[0] = 10 numbers[1] = 20 numbers[2] = 30 numbers[3] = 40 numbers[4] = 50 Iterating an Associative Array Using “for” Loop An associative array in PHP is a collection of key-value pairs. An arrow symbol (=>) is used to show the association between the key and its value. We use the array_keys() function to obtain array of keys. The following for loop prints the capital of each state from an associative array $capitals defined in the code − <?php $capitals = array( “Maharashtra”=>”Mumbai”, “Telangana”=>”Hyderabad”, “UP”=>”Lucknow”, “Tamilnadu”=>”Chennai” ); $keys=array_keys($capitals); for ($i=0; $i<count($keys); $i++){ $cap = $keys[$i]; echo “Capital of $cap is $capitals[$cap] n”; } ?> Here is its output − Capital of Maharashtra is Mumbai Capital of Telangana is Hyderabad Capital of UP is Lucknow Capital of Tamilnadu is Chennai Using Nested “for” Loops in PHP If another for loop is used inside the body of an existing loop, the two loops are said to have been nested. For each value of counter variable of the outer loop, all the iterations of inner loop are completed. <?php for ($i=1; $i<=3; $i++){ for ($j=1; $j<=3; $j++){ echo “i= $i j= $j n”; } } ?> It will produce the following output − i= 1 j= 1 i= 1 j= 2 i= 1 j= 3 i= 2 j= 1 i= 2 j= 2 i= 2 j= 3 i= 3 j= 1 i= 3 j= 2 i= 3 j= 3 Note that a string is a form of an array. The strlen() function gives the number of characters in a string. Example The following PHP script uses two nested loops to print incrementing number of characters from a

PHP – Integers

PHP – Integers ”; Previous Next Integer is one of the built-in scalar types in PHP. A whole number, without a decimal point in the literal, is of the type “int” in PHP. An integer can be represented in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation. To use octal notation, a number is preceded with “0o” or “0O” (PHP 8.1.0 and earlier). From PHP 8.1.0 onwards, a number prefixed with “0” and without a decimal point is an octal number. To use hexadecimal notation, precede the number with “0x”. To use binary notation, precede the number with “0b”. Example Take a look at this following example − <?php $a = 1234; echo “1234 is an Integer in decimal notation: $an”; $b = 0123; echo “0o123 is an integer in Octal notation: $bn”; $c = 0x1A; echo “0xaA is an integer in Hexadecimal notation: $cn”; $d = 0b1111; echo “0b1111 is an integer in binary notation: $d”; ?> It will produce the following output − 1234 is an Integer in decimal notation: 1234 0o123 is an integer in Octal notation: 83 0xaA is an integer in Hexadecimal notation: 26 0b1111 is an integer in binary notation: 15 PHP 7.4.0 onwards, integer literals may contain underscores (_) as separators between digits, for better readability of literals. These underscores are removed by PHP”s scanner. Example Take a look at this following example − <?php $a = 1_234_567; echo “1_234_567 is an Integer with _ as separator: $a”; ?> It will produce the following output − 1_234_567 is an Integer with _ as separator: 1234567 PHP does not support unsigned ints. The size of an int is platform dependent. On 32 bit systems, the maximum value is about two billion. 64-bit platforms usually have a maximum value of about 9E18. int size can be determined using the constant PHP_INT_SIZE, maximum value using the constant PHP_INT_MAX, and minimum value using the constant PHP_INT_MIN. If an integer number happens to be beyond the bounds of the int type, or any operation results in a number beyond the bounds of the int type, it will be interpreted as a float instead. Example Take a look at this following example − <?php $x = 1000000; $y = 50000000000000 * $x; var_dump($y); ?> It will produce the following output − float(5.0E+19) PHP doesn”t have any operator for integer division. Hence, a division operation between an integer and a float always results in float. To obtain integral division, you may use the intval() built-in function. Example Take a look at this following example − <?php $x = 10; $y = 3.5; $z = $x/$y; var_dump ($z); $z = intdiv($x, $y); var_dump ($z); ?> It will produce the following output − float(2.857142857142857) int(3) Print Page Previous Next Advertisements ”;

PHP – Multidimensional Array

PHP – Multidimensional Array ”; Previous Next A multidimensional array is an array of arrays. In a PHP array, each element can be another array. If the array consists of values or key-value pairs with values being of singular scalar types, it is a one-dimensional array. If each element in an array is an array of one or more scalar values, it is a two-dimensional array. A PHP array may be a two-dimensional associative array also, where each element of the outer array is key-value pair, the value being another associative array. # one dimensional indexed array $arr = [10, 20, 30, 40]; # one dimensional associative array $arr = [“key1″=> “val1”, “key2” => “val2”, “key3” => “val3”]; # two dimensional indexed array $arr = [ [1,2,3,4], [10, 20, 30, 40], [100, 200, 300, 400] ]; # two dimensional associative array $arr = [ “row1” => [“key11” => “val11”, “key12” => “val12”, “key13” => “val13”], “row2” => [“key21” => “val21”, “key22” => “val22”, “key23” => “val23”], “row3” => [“key31” => “val31”, “key32” => “val32”, “key33” => “val33”] ]; Iterating over a 2D Array Two nested loops will be needed to traverse all the elements in a 2D array. The foreach loop is more suitable for array traversal. A 2D array is like a tabular representation of data in rows and columns. Example The following example shows how you can reproduce a 2D array in a tabular form − <?php $tbl = [ [1,2,3,4], [10, 20, 30, 40], [100, 200, 300, 400] ]; echo (“n”); foreach ($tbl as $row){ foreach ($row as $elem){ $val = sprintf(“%5d”, $elem); echo $val; } echo “n”; } ?> It will produce the following output − 1 2 3 4 10 20 30 40 100 200 300 400 Example We can also employ two nested foreach loops to traverse a 2D associative array. Unpack each row of the outer array in row-key and row-value variables and traverse each row elements with the inner foreach loop. <?php $tbl = [ “row1” => [“key11” => “val11”, “key12” => “val12”, “key13” => “val13”], “row2” => [“key21” => “val21”, “key22” => “val22”, “key23” => “val23”], “row3” => [“key31” => “val31”, “key32” => “val32”, “key33” => “val33”] ]; echo (“n”); foreach ($tbl as $rk=>$rv){ echo “$rkn”; foreach ($rv as $k=>$v){ echo “$k => $v “; } echo “n”; } ?> It will produce the following output − row1 key11 => val11 key12 => val12 key13 => val13 row2 key21 => val21 key22 => val22 key23 => val23 row3 key31 => val31 key32 => val32 key33 => val33 Accessing the Elements in a 2D Array The $arr[$key] syntax of accessing and modifying an element in the array can be extended to a 2D array too. For a 2D indexed array, the jth element in the ith row can be fetched and assigned by using the expression “$arr[$i][$j]“. Example <?php $tbl = [[1,2,3,4], [10, 20, 30, 40], [100, 200, 300, 400]]; # prints number in index 2 of the row 2 print (“Value at [2], [2] :” . $tbl[2][2]); ?> It will produce the following output − Value at [2], [2] :300 Similarly, the value at ith row and jth column may be set to another value. $tbl[2][2] = 250; Example If it is a 2D associative array, we need to use the row key and key-value variables of the desired column to access or modify its value. <?php $tbl = [ “row1” => [“key11” => “val11”, “key12” => “val12”, “key13” => “val13”], “row2” => [“key21” => “val21”, “key22” => “val22”, “key23” => “val23”], “row3” => [“key31” => “val31”, “key32” => “val32”, “key33” => “val33”] ]; print “value at row2 – key22 is ” . $tbl[“row2”][“key22”]; ?> It will produce the following output − value at row2 – key22 is val22 Multi-dimensional Array In the above example, we had an array in which the associated value of each key was another collection of key-value pairs, and we call it as a 2D array. The concept can be extended to any number of levels. For example, if each element in the inner array associates its key to another array, it becomes a three-dimensional array. Here is an example of a three-dimensional array − $arr3D = [ [ [1, 0, 9], [0, 5, 6], [1, 0, 3] ], [ [0, 4, 6], [0, 0, 1], [1, 2, 7] ], ]; Example To traverse such a 3D array, we need three nested foreach loops, as shown below − <?php $arr3D = [ [[1, 0, 9],[0, 5, 6],[1, 0, 3]], [[0, 4, 6],[0, 0, 1],[1, 2, 7]], ]; foreach ($arr3D as $arr) { foreach ($arr as $row) { foreach ($row as $element) { echo “$element “; } echo “n”; } echo “n”; } ?> It will produce the following output − 1 0 9 0 5 6 1 0 3 0 4 6 0 0 1 1 2 7 However, it is entirely possible to declare an array extending upto any number of dimensions. For that we need to have a generalized solution to traverse an array of any dimensions. Recurve Traversal of Multidimensional Array The following code shows a recursive function that calls itself if the value of a certain key is another array. If we pass any array as an argument to this function, it will be traversed, showing all the k-v pairs in it. function showarray($arr) { foreach ($arr as $k=>$v) { if (is_array($v)) { showarray($v); } else { echo “$k => $v “; } } echo “n”; } Example Let us pass the above 3D array $arr3D to it

PHP – Date & Time

PHP – Date & Time ”; Previous Next The built-in library of PHP has a wide range of functions that helps in programmatically handling and manipulating date and time information. Date and Time objects in PHP can be created by passing in a string presentation of date/time information, or from the current system”s time. PHP provides the DateTime class that defines a number of methods. In this chapter, we will have a detailed view of the various Date and Time related methods available in PHP. The date/time features in PHP implements the ISO 8601 calendar, which implements the current leap-day rules from before the Gregorian calendar was in place. The date and time information is internally stored as a 64-bit number. Getting the Time Stamp with time() PHP”s time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer. time(): int The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp. <?php print time(); ?> It will produce the following output − 1699421347 We can convert a time stamp into a form that humans are comfortable with. Converting a Time Stamp with getdate() The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time(). The following table lists the elements contained in the array returned by getdate(). Sr.No Key & Description Example 1 seconds Seconds past the minutes (0-59) 20 2 minutes Minutes past the hour (0 – 59) 29 3 hours Hours of the day (0 – 23) 22 4 mday Day of the month (1 – 31) 11 5 wday Day of the week (0 – 6) 4 6 mon Month of the year (1 – 12) 7 7 year Year (4 digits) 1997 8 yday Day of year ( 0 – 365 ) 19 9 weekday Day of the week Thursday 10 month Month of the year January 11 0 Timestamp 948370048 Now you have complete control over date and time. You can format this date and time in whatever format you want. Example Take a look at this following example − <?php $date_array = getdate(); foreach ( $date_array as $key => $val ){ print “$key = $valn”; } $formated_date = “Today”s date: “; $formated_date .= $date_array[”mday”] . “-“; $formated_date .= $date_array[”mon”] . “-“; $formated_date .= $date_array[”year”]; print $formated_date; ?> It will produce the following output − seconds = 0 minutes = 38 hours = 6 mday = 8 wday = 3 mon = 11 year = 2023 yday = 311 weekday = Wednesday month = November 0 = 1699421880 Today”s date: 8-11-2023 Converting a Time Stamp with date() The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it. date(string $format, ?int $timestamp = null): string The date() optionally accepts a time stamp if omitted then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value. The following table lists the codes that a format string can contain − Sr.No Format & Description Example 1 a ”am” or ”pm” lowercase pm 2 A ”AM” or ”PM” uppercase PM 3 d Day of month, a number with leading zeroes 20 4 D Day of week (three letters) Thu 5 F Month name January 6 h Hour (12-hour format – leading zeroes) 12 7 H Hour (24-hour format – leading zeroes) 22 8 g Hour (12-hour format – no leading zeroes) 12 9 G Hour (24-hour format – no leading zeroes) 22 10 i Minutes ( 0 – 59 ) 23 11 j Day of the month (no leading zeroes 20 12 l (Lower ”L”) Day of the week Thursday 13 L Leap year (”1” for yes, ”0” for no) 1 14 m Month of year (number – leading zeroes) 1 15 M Month of year (three letters) Jan 16 r The RFC 2822 formatted date Thu, 21 Dec 2000 16:01:07 +0200 17 n Month of year (number – no leading zeroes) 2 18 s Seconds of hour 20 19 U Time stamp 948372444 20 y Year (two digits) 06

PHP – Echo/Print

PHP – Echo/Print ”; Previous Next In PHP, both echo and print statements are used to render the output either on the browser or the PHP console. Both of them are not functions but they are language constructs. Hence, parentheses should not be used with either of them. The “echo” Statement in PHP The echo statement is used with following syntax − echo(string …$expressions): void The echo statement outputs one or more expressions, with no additional newlines or spaces. Example Here is an example of how the echo statement works in PHP − <?php $name = “Rajesh”; echo “Hello ” . $name . ” How are you?” ?> It will produce the following output − Hello Rajesh How are you? Since a double quoted string is similar to a single quoted string in PHP, the following statement produces the same output. echo ”Hello ” . $name . ” How are you?”; Example A double quoted string outputs the value of the variable. Hence, the following statement inserts the value of “$name” variable before printing the output. <?php $name = “Rajesh”; echo “Hello $name How are you?”; ?> It will produce the following output − Hello Rajesh How are you? Example But, a single-quoted string will output “$name” as it is. <?php $name = “Rajesh”; echo ”Hello $name How are you?”; ?> It will produce the following output − Hello $name How are you? A string passed to an echo statement can either be passed individually as multiple arguments or concatenated together and passed as a single argument. So, both the following statements are valid − echo ”Hello ”, ”how ”, ”are ”, ”you?”, “n”; echo ”Hello ” . ”how ” . ”are ” . ”you?” . “n”; Example Note that output of the two successive echo statements will be rendered in the same line if the newline character is not used. Take a look at the following example − <?php echo “hello”; echo “world”; ?> It will produce the following output − helloworld The “print” Statement in PHP The print statement is similar to echo, but it outputs an expression. print(string $expression): int Like echo, print is also a language construct. Its argument is an expression but it is not put in parentheses. The major difference is that the print statement in PHP accepts a single argument only and always returns 1. Example Take a look at this following example − <?php $name = “Rajesh”; print “Hello ” . $name . ” How are you?n”; print “Hello $name How are you?”; ?> It will produce the following output − Hello Rajesh How are you? Hello Rajesh How are you? Output Multiline Strings Using Print/Echo Both echo and print statements can output multiline strings spanning over more than one lines in the editor. Take a look at the following example − <?php print “ Multi-line string can be output by echo as well as print statement in PHP “; ?> It will produce the following output − Multi-line string can be output by echo as well as print statement in PHP The output will remain the same if we replace print with echo. Print Page Previous Next Advertisements ”;

PHP – Data Types

PHP – Data Types ”; Previous Next The term “data types” refers to the classification of data in distinct categories. PHP has a total of eight data types that we use to construct our variables − Integers − Whole numbers, without a decimal point, like 4195. Doubles − Floating-point numbers like 3.14159 or 49.1. Booleans − Have only two possible values, either true or false. NULL − Special type that only has one value: NULL. Strings − Sequences of characters, like ”PHP supports string operations.” Arrays − Named and indexed collections of other values. Objects − Instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class. Resources − Special variables that hold references to resources external to PHP (such as database connections). The first five are simple types, and the next two (arrays and objects) are compound types. The compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot. In this chapter, let”s discuss in detail about these built-in data types of PHP. Integer Data Type in PHP A whole number without a decimal point (like 4195) is of int type in PHP. Integer data types are the simplest type. They correspond to simple whole numbers, both positive and negative. An int is a number of the set Z = {…, -2, -1, 0, 1, 2, …}. An int can be represented in a decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation. To use octal notation, a number is preceded with “0o” or “0O”. To use hexadecimal notation, precede the number with “0x”. To use binary notation, precede the number with “0b”. Given below are some examples − Decimal Integer − 201, 4195, -15 Octal Integer − 0010, 0O12, -0O21 Hexadecimal Integer − 0x10, -0x100 Binary Integer − 0b10101, -0b100 Integers can be assigned to variables, or they can be used in expressions, like so − $int_var = 12345; $another_int = -12345 + 12345; Double Data Type in PHP Double variables represent floating point numbers (also known as “floats”, “doubles”, or “real numbers”) that are the numbers with a fractional component. The fractional component follows after the integer component separated by the decimal symbol (.) Note − A double variable can be positive, negative, or zero. $var1 = 1.55 $var2 =-123.0 Scientific Float Notation PHP also allows the use of scientific notation to represent a floating point number with more digits after the decimal point. The symbol “E” or “e” is used to separate the integer and fractional part. − 1.2e3, 2.33e-4, 7E-10, 1.0E5 By default, doubles print with the minimum number of decimal places needed. Take a look at the following example − <?php $many = 2.2888800; $many_2 = 2.2111200; $few = $many + $many_2; print(“$many + $many_2 = $few”); ?> It produces the following output − 2.28888 + 2.21112 = 4.5 Boolean Data Type in PHP The bool type only has only two values; it can either be True or False. The bool type is used to express a truth value. $bool1 = true; $bool2 = false; You can also use the integer values “1” and “0” to represent True and False Boolean values − $bool3 = 1; $bool4 = 0; Typically, the result of an operator which returns a bool value is passed on to a control structure such as if, while or do-while. For example, if (TRUE) print(“This will always print.”); else print(“This will never print.”); Interpreting Other Data Types as Booleans Here is a set of rules that you can use to interpret other data types as Booleans − If the value is a number, then it is False only if the value is equal to zero, otherwise the value is True. If the value is a string, it is False if the string is empty (has zero characters) or is the string “0”, and is True otherwise. The values of type NULL are always False. If the value is an array, it is False if it contains no other values; True otherwise. For an object, containing a value means having a member variable that has been assigned a value. Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful). Note − Don”t use double as Booleans. Each of the following variables has the truth value embedded in its name when it is used in a Boolean context. $true_num = 3 + 0.14159; $true_str = “Tried and true” $true_array[49] = “An array element”; $false_array = array(); $false_null = NULL; $false_num = 999 – 999; $false_str = “”; String Data Type in PHP A string is a sequence of characters, for example, ”PHP supports string operations.” In PHP, a character is the same as a byte. It means PHP only supports a 256 character set, and hence does not offer native Unicode support. PHP supports single-quoted as well as double-quoted string formation. Both the following representations are valid in PHP − $string_1 = “This is a string in double quotes”; $string_2 = ”This is a somewhat longer, singly quoted string”; Here are some more examples of string type − $string_39 = “This string has thirty-nine characters”; $string_0 = “”; // a string with zero characters Single-quoted strings are treated almost literally, whereas double-quoted strings replace variables with their values as well as specially interpreting certain character sequences. <?php $variable = “name”; $literally = ”My

PHP – Scalar Type Declarations

PHP – Scalar Type Declarations ”; Previous Next The feature of providing type hints has been in PHP since version 5. Type hinting refers to the practice of providing the data type of a parameter in the function definition. Before PHP 7, it was possible to use only the array, callable, and class for type hints in a function. PHP 7 onwards, you can also insert type hints for parameters of scalar data type such as int, string, bool, etc. PHP is a dynamically (and weakly) typed language. Hence, you don’t need to declare the type of the parameter when a function is defined, something which is necessary in a statically type language like C or Java. A typical definition of function in PHP is as follows − function addition($x, $y) { echo “First number: $x Second number: $y Addition: ” . $x+$y; } Here, we assume that the parameters $x and $y are numeric. However, even if the values passed to the function aren’t numeric, the PHP parser tries to cast the variables into compatible type as far as possible. If one of the values passed is a string representation of a number, and the second is a numeric variable, PHP casts the string variable to numeric in order to perform the addition operation. Example Take a look at this following example − <?php function addition($x, $y) { echo “First number: ” . $x; echo “nSecond number: ” . $y; echo “nAddition: ” . $x+$y; } $x=”10″; $y=20; addition($x, $y); ?> It will produce the following output − First number: 10 Second number: 20 Addition: 30 However, if $x in the above example is a string that doesn’t hold a valid numeric representation, an error is encountered. <?php function addition($x, $y) { echo “First number: ” . $x; echo “nSecond number: ” . $y; echo “nAddition: ” . $x+$y; } $x=”Hello”; $y=20; addition($x, $y); ?> Run this code and see how it shows an error. Scalar Type Declarations in PHP 7 A new feature introduced with PHP version 7 allows defining a function with parameters whose data type can be specified within the parenthesis. PHP 7 has introduced the following Scalar type declarations − Int Float Bool String Interfaces Array Callable Older versions of PHP allowed only the array, callable and class types to be used as type hints. Furthermore, in the older versions of PHP (PHP 5), the fatal error used to be a recoverable error while the new release (PHP 7) returns a throwable error. Scalar type declaration is implemented in two modes − Coercive Mode − Coercive is the default mode and need not to be specified. Strict Mode − Strict mode has to be explicitly hinted. Coercive Mode The addition() function defined in the earlier example can now be re-written by incorporating the type declarations as follows − function addition(int $x, int $y) { echo “First number: $x Second number: $y Addition: ” . $x+$y; } Note that the parser still casts the incompatible types i.e., string to an int if the string contains an integer as earlier. Example Take a look at this following example − <?php function addition(int $x, int $y) { echo “First number: ” . $x; echo “nSecond number: ” . $y; echo “nAddition: ” . $x+$y; } $x=”10″; $y=20; echo addition($x, $y); ?> It will produce the following output − First number: 10 Second number: 20 Addition: 30 Obviously, this is because PHP is a weakly typed language, as PHP tries to coerce a variable of string type to an integer. PHP 7 has introduced a strict mode feature that addresses this issue. Strict Mode To counter the weak type checking of PHP, a strict mode has been introduced. This mode is enabled with a declare statement − declare (strict_types=1); You should put this statement at the top of the PHP script (usually just below the PHP tag). This means that the strictness of typing for scalars is configured on a per-file basis. In the weak mode, the strict_types flag is 0. Setting it to 1 forces the PHP parser to check the compatibility of the parameters and values passed. Add this statement in the above code and check the result. It will show the following error message − Fatal error: Uncaught TypeError: addition(): Argument #1 ($x) must be of type int, string given, called in add.php on line 12 and defined in add.php:4 Stack trace: #0 add.php(12): addition(”10”, 20) #1 {main} thrown in add.php on line 4 Example Here is another example of scalar type declaration in the function definition. The strict mode when enabled raises fatal error if the incompatible types are passed as parameters. <?php // Strict mode // declare(strict_types = 1); function sum(int …$ints) { return array_sum($ints); } print(sum(2, ”3”, 4.1)); ?> Uncomment the declare statement at the top of this code and run it. Now it will produce an error − Fatal error: Uncaught TypeError: sum(): Argument #2 must be of type int, string given, called in add.php on line 9 and defined in add.php:4 Stack trace: #0 add.php(9): sum(2, ”3”, 4.1) #1 {main} thrown in add.php on line 4 The type-hinting feature is mostly used by IDEs to prompt the user about the expected types of the parameters used in the function declaration. The following screenshot shows the VS Code editor popping up the function prototype as you type. Print Page Previous Next

PHP – Comments

PHP – Comments ”; Previous Next A comment in any computer program (such as a PHP program) is a certain explanatory text that is ignored by the language compiler/interpreter. Its purpose is to help the user understand the logic used in the program algorithm. Although placing comments in the code is not essential, it is a highly recommended practice. The comments also serve as program documentation. Comments are also useful when the code needs to be debugged and modified. There are two commenting formats in PHP − Single-line Comments Multi-line Comments Single-line Comments They are generally used for short explanations or notes relevant to the local code. PHP uses two notations for inserting a single-line comment in a program. Single-line Comments Using “#” A line in PHP code starting with the “#” symbol is treated as a single-line comment. <?php # Single line comment starting with # symbol echo ”Hello World”; ?> Single-line Comments Using “//” PHP also supports C style of single-line comments with “//” symbol. A line starting with double oblique symbol is treated as a comment. <?php // Single line comment starting with // symbol echo ”Hello World”; ?> A comment that starts with the symbol “#” or “//” need not be closed. The effect of these symbols last till the end of the physical line. In other words, the PHP parser will treat the next line as a PHP statement and not as a comment even if there is no closing comment marker. Multi-line Comments Multi-line comments are generally used to provide pseudocode algorithms and more detailed explanations when necessary. The multiline style of commenting is the same as in C. One or more lines embedded inside the “/*” and “*/” symbols are treated as a comment. Example of Multi-line Comment in PHP Here is the example of a multi-line comment. <?php /* This is a multiline comment example program to add two numbers Variables used – $x for first number, $y for second number */ $x=10; $y=20; print “Total = “. $x+$y; ?> Note that you can put even a single line inside the “/* .. */” symbols. However, if there is a “/*” symbol in the program, it must have a closing end-of comment marker “*/”. If not, an error will be displayed as follows − PHP Parse error: Unterminated comment starting line 3 in /home/cg/root/65ded9eeb52fc/main.php on line 3 Print Page Previous Next Advertisements ”;

PHP – Constants

PHP – Constants ”; Previous Next A constant in PHP is a name or an identifier for a simple value. A constant value cannot change during the execution of the PHP script. By default, a PHP constant is case-sensitive. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscore. There is no need to write a dollar sign ($) before a constant, however one has to use a dollar sign before a variable. Examples of Valid and Invalid Constant Names in PHP Here are some examples of valid and invalid constant names in PHP − // Valid constant names define(“ONE”, “first thing”); define(“TWO2”, “second thing”); define(“THREE_3”, “third thing”); define(“__THREE__”, “third value”); // Invalid constant names define(“2TWO”, “second thing”); Difference between Constants and Variables in PHP Constants cannot be defined by simple assignment; they can only be defined using the define() function. Constants may be defined and accessed anywhere without regard to variable scoping rules. Once the Constants have been set, they may not be redefined or undefined. Defining a Named Constant The define() function in PHP library is used to define a named constant at runtime. define(string $const_name, mixed $value, bool $case = false): bool Parameters const_name − The name of the constant. value − The value of the constant. It can be a scalar value (int, float, string, bool, or null) or array values are also accepted. case − If set to true, the constant will be defined case-insensitive. The default behavior is case-sensitive, i.e., CONSTANT and Constant represent different values. The define() function returns “true” on success and “false” on failure. Example 1 The following example demonstrates how the define() function works − <?php define(“CONSTANT”, “Hello world.”); echo CONSTANT; // echo Constant; ?> The first echo statement outputs the value of CONSTANT. You will get the following output − Hello world. But, when you uncomment the second echo statement, it will display the following error − Fatal error: Uncaught Error: Undefined constant “Constant” in hello.php: on line 5 If you set the case parameter to False, PHP doesn’t differentiate upper and lowercase constants. Example 2 You can also use an array as the value of a constant. Take a look at the following example − <?php define( $name=”LANGS”, $value=array(”PHP”, ”Java”, ”Python”) ); var_dump(LANGS); ?> It will produce the following output − array(3) { [0]=> string(3) “PHP” [1]=> string(4) “Java” [2]=> string(6) “Python” } Using the constant() Function The echo statement outputs the value of the defined constant. You can also use the constant() function. It returns the value of the constant indicated by name. constant(string $name): mixed The constant() function is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function. <?php define(“MINSIZE”, 50); echo MINSIZE; echo PHP_EOL; echo constant(“MINSIZE”); // same thing as the previous line ?> It will produce the following output − 50 50 Using the defined() Function The PHP library provides a defined() function that checks whether a given named constant exists. Take a look at the following example − <?php define(”MAX”, 100); if (defined(”MAX”)) { echo MAX; } ?> It will produce the following output − 100 PHP also has a function called “get_defined_constants()” that returns an associative array of all the defined constants and their values. Print Page Previous Next Advertisements ”;