PHP – $_FILES ”; Previous Next $_FILES is one of the ”superglobal”, or automatic global, variables in PHP. It is available in all scopes throughout a script. The variable $_FILES is an associative array containing items uploaded via HTTP POST method. A file is uploaded when a HTML form contains an input element with a file type, its enctype attribute set to multipart/form-data, and the method attribute set to HTTP POST method. $HTTP_POST_FILES also contains the same information, but it is not a superglobal, and it has now been deprecated. The following HTML script contains a form with input element of file type − <input type=”file” name=”file”> This “input type” renders a button captioned as file. When clicked, a file dialogbox pops up. You can choose a file to be uploaded. The PHP script on the server can access the file data in $_FILES variable. The $_FILES array contains the following properties − $_FILES[”file”][”name”] − The original name of the file that the user has chosen to be uploaded. $_FILES[”file”][”type”] − The mime type of the file. An example would be “image/gif”. This mime type is however not checked on the PHP side. $_FILES[”file”][”size”] − The size, in bytes, of the uploaded file. $_FILES[”file”][”tmp_name”] − The temporary filename of the file in which the uploaded file was stored on the server. $_FILES[”file”][”full_path”] − The full path as submitted by the browser. Available as of PHP 8.1.0. $_FILES[”file”][”error”] − The error code associated with this file upload. The error codes are enumerated as below − Error Codes Description UPLOAD_ERR_OK (Value=0) There is no error, the file uploaded with success. UPLOAD_ERR_INI_SIZE (Value=1) The uploaded file exceeds the upload_max_filesize directive in php.ini. UPLOAD_ERR_FORM_SIZE (Value=2) The uploaded file exceeds the MAX_FILE_SIZE. UPLOAD_ERR_PARTIAL (Value=3) The uploaded file was only partially uploaded. UPLOAD_ERR_NO_FILE (Value=4) No file was uploaded. UPLOAD_ERR_NO_TMP_DIR (Value=6) Missing a temporary folder. UPLOAD_ERR_CANT_WRITE (Value=7) Failed to write file to disk. UPLOAD_ERR_EXTENSION (Value=8) A PHP extension stopped the file upload. Example The following “test.html” contains a HTML form whose enctype is set to multiform/form-data. It also has an input file element which presents a button on the form for the user to select file to be uploaded. Save this file in the document root folder of your Apache server. <html> <body> <form action=”hello.php” method=”POST” enctype=”multipart/form-data”> <p><input type=”file” name=”file”></p> <p><input type =”submit” value=”submit”></p> </form> </body> </html> The above HTML renders a button named “Choose File” in the browser window. To open a file dialog box, click the “Choose File” button. As the name of selected file appears, click the submit button. Example The server-side PHP script (upload.php) in the document root folder reads the variables $_FILES array as follows − <?php echo “Filename: ” . $_FILES[”file”][”name”].”<br>”; echo “Type : ” . $_FILES[”file”][”type”] .”<br>”; echo “Size : ” . $_FILES[”file”][”size”] .”<br>”; echo “Temp name: ” . $_FILES[”file”][”tmp_name”] .”<br>”; echo “Error : ” . $_FILES[”file”][”error”] . “<br>”; ?> It will produce the following output − Filename: abc.txt Type : text/plain Size : 556762 Temp name: C:xampptmpphpD833.tmp Error : 0 Example In PHP, you can upload multiple files using the HTML array feature − <html> <body> <form action=”hello.php” method=”POST” enctype=”multipart/form-data”> <input type=”file” name=”files[]”/> <input type=”file” name=”files[]”/> <input type =”submit” value=”submit”/> </form> </body> </html> Now, change the PHP script (hello.php) to − <?php foreach ($_FILES[“files”][“name”] as $key => $val) { echo “File uploaded: $val <br>”; } ?> The browser will show multiple “Choose File” buttons. After you upload the selected files by clicking the “Submit” button, the browser will show the names of files in response to the URL http://localhost/hello.html as shown below − Print Page Previous Next Advertisements ”;
Category: php
PHP – $_GET
PHP – $_GET ”; Previous Next $_GET is one of the superglobals in PHP. It is an associative array of variables passed to the current script via the query string appended to the URL of HTTP request. Note that the array is populated by all requests with a query string in addition to GET requests. $HTTP_GET_VARS contains the same initial information, but that has now been deprecated. By default, the client browser sends a request for the URL on the server by using the HTTP GET method. A query string attached to the URL may contain key value pairs concatenated by the “&” symbol. The $_GET associative array stores these key value pairs. Save the following script in the document folder of Apache server. If you are using XAMPP server on Windows, place the script as “hello.php” in the “c:/xampp/htdocs” folder. <?php echo “<h3>First Name: ” . $_REQUEST[”first_name”] . “<br />” . “Last Name: ” . $_REQUEST[”last_name”] . “</h3>”; ?> Start the XAMPP server, and enter “http://localhost/hello.php?first_name=Mukesh&last_name=Sinha” as the URL in a browser window. You should get the following output − The $_GET array is also populated when a HTML form data is submitted to a URL with GET action. Under the document root, save the following script as “hello.html” − <html> <body> <form action=”hello.php” method=”get”> <p>First Name: <input type=”text” name=”first_name”/></p> <p>Last Name: <input type=”text” name=”last_name” /></p> <input type=”submit” value=”Submit” /> </form> </body> </html> In your browser, enter the URL “http://localhost/hello.html” − You should get a similar output in the browser window − In the following example, htmlspecialchars() is used to convert characters in HTML entities − Character Replacement & (ampersand) & ” (double quote) " ” (single quote) ' or ' < (less than) < > (greater than) > Assuming that the URL in the browser is “http://localhost/hello.php?name=Suraj&age=20” − <?php echo “Name: ” . htmlspecialchars($_GET[“name”]) . “”; echo “Age: ” . htmlspecialchars($_GET[“age”]) . “<br/>”; ?> It will produce the following output − Name: Suraj Age: 20 Print Page Previous Next Advertisements ”;
PHP – Named Arguments
PHP – Named Arguments ”; Previous Next The feature of Named Arguments has been introduced in PHP with the version 8.0. It is an extension of the existing mechanism of passing positional arguments to a function while calling. By default, values of passed arguments are copied to the corresponding formal arguments at the same position. This feature of named arguments in PHP makes it possible to pass the value based on the parameter name instead of the position. If we have a function defined as follows − function myfunction($x, $y) { statement1; statement2; . . . } and it is called as − myfunction(10, 20); In this case, the values are passed to the variables “x” and “y” in the order of declaration. It means, the first value to the first argument, second value to second argument and so on. The variables “x” and “y” are positional arguments. To pass the values by named arguments, specify the parameter name to which argument the value is to be passed. The name of the parameter is the name of formal argument without the “$” symbol. The value to be passed is put in front of the “:” symbol. myfunction(x:10, y:20); Example Here is the code that demonstrates how you can use named arguments in PHP − <?php function myfunction($x, $y) { echo “x = $x y = $y”; } myfunction(x:10, y:20); ?> It will produce the following output − x = 10 y = 20 Using named arguments makes it possible to pass the values in any order, and not necessarily in the same order in which the arguments are declared in the function definition. We can call myfunction() as shown below and it will produce the same result. myfunction(y:20, x:10); With this feature, the arguments become order-independent and self-documenting. It also makes it possible to skip the arguments with default values arbitrarily. Combining Named Arguments with Positional Arguments Named arguments can be combined with positional arguments, with the condition that, the named arguments must come after the positional arguments. Example <?php function myfunction($x, $y, $z) { echo “x = $x y = $y z = $z”; } myfunction(10, z:20, y:30); ?> It will produce the following output − x = 10 y = 30 z = 20 However, if you try to treat $z as a positional argument, myfunction(x:10, y:20, 30); In this case, PHP will encounter the following error − PHP Fatal error: Cannot use positional argument after named argument in hello.php on line 7 Passing Named Arguments from an Array PHP 8.1.0 also introduced another feature that allows using named argument after unpacking the arguments. Instead of providing values to each argument individually, the values in an array an be unpacked into the corresponding arguments, using “…” (three dots) before the array. Example <?php function myfunction($x, $y, $z=30) { echo “x = $x y = $y z = $z”; } myfunction(…[10, 20], z:30); ?> It will produce the following output − x = 10 y = 20 z = 30 Note that passing the same parameter multiple times results in an exception as follows − myfunction(x:10, z:20, x:20); Error − PHP Fatal error: Uncaught Error: Named parameter $x overwrites previous argument in hello.php:7 Print Page Previous Next Advertisements ”;
PHP – Call by value
PHP – Call by Value ”; Previous Next By default, PHP uses the “call by value” mechanism for passing arguments to a function. When a function is called, the values of actual arguments are copied to the formal arguments of the function’s definition. During the execution of the function body, if there is any change in the value of any of the formal arguments, it is not reflected in the actual arguments. Actual Arguments − The arguments that are passed in a function call. Formal Arguments − The arguments that are declared in a function definition. Example Let us consider the function used in the code below − <?php function change_name($nm) { echo “Initially the name is $nm n”; $nm = $nm.”_new”; echo “This function changes the name to $nm n”; } $name = “John”; echo “My name is $name n”; change_name($name); echo “My name is still $name”; ?> It will produce the following output − My name is John Initially the name is John This function changes the name to John_new My name is still John In this example, the change_name() function appends _new to the string argument passed to it. However, the value of the variable that was passed to it remains unchanged after the function’s execution. Formal arguments, in fact, behave as local variables for the function. Such a variable is accessible only inside the scope in which it is initialized. For a function, its body marked by the curly brackets “{ }” is its scope. Any variable inside this scope is not available for the code outside it. Hence, manipulation of any local variable has no effect on the world outside. The “call by value” method is suitable for a function that uses the values passed to it. It performs certain computation and returns the result without having to change the value of parameters passed to it. Note − Any function that performs a formula-type computation is an example of call by value. Example Take a look at the following example − <?php function addFunction($num1, $num2) { $sum = $num1 + $num2; return $sum; } $x = 10; $y = 20; $num = addFunction($x, $y); echo “Sum of the two numbers is : $num”; ?> It will produce the following output − Sum of the two numbers is : 30 Example Here is another example of calling a function by passing the argument by value. The function increments the received number by 1, but that doesn’t affect the variable passed to it. <?php function increment($num) { echo “The initial value: $num n”; $num++; echo “This function increments the number by 1 to $num n”; } $x = 10; increment($x); echo “Number has not changed: $x”; ?> It will produce the following output − The initial value: 10 This function increments the number by 1 to 11 Number has not changed: 10 PHP also supports passing the reference of variables to the function while calling. We shall discuss it in the next chapter. Print Page Previous Next Advertisements ”;
PHP – Arrays
PHP – Arrays ”; Previous Next An array is a data structure that stores one or more data values having some relation among them, in a single variable. For example, if you want to store the marks of 10 students in a class, then instead of defining 10 different variables, it’s easy to define an array of 10 length. Arrays in PHP behave a little differently than the arrays in C, as PHP is a dynamically typed language as against C which is a statically type language. An array in PHP is an ordered map that associates values to keys. A PHP array can be used to implement different data structures such as a stack, queue, list (vector), hash table, dictionary, etc. The value part of an array element can be other arrays. This fact can be used to implement tree data structure and multidimensional arrays. There are two ways to declare an array in PHP. One is to use the built-in array() function, and the other is to use a shorter syntax where the array elements are put inside square brackets. The array() Function The built-in array() function uses the parameters given to it and returns an object of array type. One or more comma-separated parameters are the elements in the array. array(mixed …$values): array Each value in the parenthesis may be either a singular value (it may be a number, string, any object or even another array), or a key-value pair. The association between the key and its value is denoted by the “=>” symbol. Examples $arr1 = array(10, “asd”, 1.55, true); $arr2 = array(“one”=>1, “two”=>2, “three”=>3); $arr3 = array( array(10, 20, 30), array(“Ten”, “Twenty”, “Thirty”), array(“physics”=>70, “chemistry”=>80, “maths”=>90) ); Using Square Brackets [ ] Instead of the array() function, the comma-separated array elements may also be put inside the square brackets to declare an array object. In this case too, the elements may be singular values or a string or another array. $arr1 = [10, “asd”, 1.55, true]; $arr2 = [“one”=>1, “two”=>2, “three”=>3]; $arr3 = [ [10, 20, 30], [“Ten”, “Twenty”, “Thirty”], [“physics”=>70, “chemistry”=>80, “maths”=>90] ]; Types of Arrays in PHP There are three different kind of arrays and each array value is accessed using an ID which is called the array index. Indexed Array − An array which is a collection of values only is called an indexed array. Each value is identified by a positional index staring from “0”. Values are stored and accessed in linear fashion. Associative Array − If the array is a collection of key-value pairs, it is called as an associative array. The key component of the pair can be a number or a string, whereas the value part can be of any type. Associative arrays store the element values in association with key values rather than in a strict linear index order. Multi Dimensional Array − If each value in either an indexed array or an associative array is an array itself, it is called a multi dimensional array. Values are accessed using multiple indices NOTE − Built-in array functions is given in function reference PHP Array Functions It may be noted that PHP internally considers any of the above types as an associative array itself. In case of an indexed array, where each value has index, the index itself is its key. The var_dump() function reveals this fact. Example In this example, arr1 is an indexed array. However, var_dump()which displays the structured information of any object, shows that each value is having its index as its key. <?php $arr1 = [10, “asd”, 1.55, true]; var_dump($arr1); ?> It will produce the following output − array(4) { [0]=> int(10) [1]=> string(3) “asd” [2]=> float(1.55) [3]=> bool(true) } Example The same principle applies to a multi-dimensional index array, where each value in an array is another array. <?php $arr1 = [ [10, 20, 30], [“Ten”, “Twenty”, “Thirty”], [1.1, 2.2, 3.3] ]; var_dump($arr1); ?> It will produce the following output − array(3) { [0]=> array(3) { [0]=> int(10) [1]=> int(20) [2]=> int(30) } [1]=> array(3) { [0]=> string(3) “Ten” [1]=> string(6) “Twenty” [2]=> string(6) “Thirty” } [2]=> array(3) { [0]=> float(1.1) [1]=> float(2.2) [2]=> float(3.3) } } Accessing the Array Elements To access any element from a given array, you can use the array[key] syntax. Example For an indexed array, put the index inside the square bracket, as the index itself is anyway the key. <?php $arr1 = [10, 20, 30]; $arr2 = array(“one”=>1, “two”=>2, “three”=>3); var_dump($arr1[1]); var_dump($arr2[“two”]); ?> It will produce the following output − int(20) int(2) We shall explore the types of PHP arrays in more details in the subsequent chapters. Print Page Previous Next Advertisements ”;
PHP – Logical Operators
PHP – Logical Operators Examples ”; Previous Next In PHP, logical operators are used to combine conditional statements. These operators allow you to create more complex conditions by combining multiple conditions together. Logical operators are generally used in conditional statements such as if, while, and for loops to control the flow of program execution based on specific conditions. The following table highligts the logical operators that are supported by PHP. Assume variable $a holds 10 and variable $b holds 20, then − Operator Description Example and Called Logical AND operator. If both the operands are true then condition becomes true. (A and B) is true or Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A or B) is true && Called Logical AND operator. The AND operator returns true if both the left and right operands are true. (A && B) is true || Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (A || B) is true ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false Example The following example shows how you can use these logical operators in PHP − <?php $a = 42; $b = 0; if ($a && $b) { echo “TEST1 : Both a and b are true n”; } else { echo “TEST1 : Either a or b is false n”; } if ($a and $b) { echo “TEST2 : Both a and b are true n”; } else { echo “TEST2 : Either a or b is false n”; } if ($a || $b) { echo “TEST3 : Either a or b is true n”; } else { echo “TEST3 : Both a and b are false n”; } if ($a or $b) { echo “TEST4 : Either a or b is true n”; } else { echo “TEST4 : Both a and b are false n”; } $a = 10; $b = 20; if ($a) { echo “TEST5 : a is true n”; } else { echo “TEST5 : a is false n”; } if ($b) { echo “TEST6 : b is true n”; } else { echo “TEST6 : b is false n”; } if (!$a) { echo “TEST7 : a is true n”; } else { echo “TEST7 : a is false n”; } if (!$b) { echo “TEST8 : b is true n”; } else { echo “TEST8 : b is false”; } ?> It will produce the following output − TEST1 : Either a or b is false TEST2 : Either a or b is false TEST3 : Either a or b is true TEST4 : Either a or b is true TEST5 : a is true TEST6 : b is true TEST7 : a is false TEST8 : b is false Print Page Previous Next Advertisements ”;
PHP – Return Type Declarations ”; Previous Next PHP version 7 extends the scalar type declaration feature to the return value of a function also. As per this new provision, the return type declaration specifies the type of value that a function should return. We can declare the following types for return types − int float bool string interfaces array callable To implement the return type declaration, a function is defined as − function myfunction(type $par1, type $param2): type { # function body return $val; } PHP parser is coercive typing by default. You need to declare “strict_types=1” to enforce stricter verification of the type of variable to be returned with the type used in the definition. Example In the following example, the division() function is defined with a return type as int. <?php function division(int $x, int $y): int { $z = $x/$y; return $z; } $x=20.5; $y=10; echo “First number: ” . $x; echo “nSecond number: ” . $y; echo “nDivision: ” . division($x, $y); ?> Since the type checking has not been set to strict_types=1, the division take place even if one of the parameters is a non-integer. First number: 20.5 Second number: 10 Division: 2 However, as soon as you add the declaration of strict_types at the top of the script, the program raises a fatal error message. Fatal error: Uncaught TypeError: division(): Argument #1 ($x) must be of type int, float given, called in div.php on line 12 and defined in div.php:3 Stack trace: #0 div.php(12): division(20.5, 10) #1 {main} thrown in div.php on line 3 VS Code warns about the error even before running the code by displaying error lines at the position of error − Example To make the division() function return a float instead of int, cast the numerator to float, and see how PHP raises the fatal error − <?php // declare(strict_types=1); function division(int $x, int $y): int { $z = (float)$x/$y; return $z; } $x=20; $y=10; echo “First number: ” . $x; echo “nSecond number: ” . $y; echo “nDivision: ” . division($x, $y); ?> Uncomment the declare statement at the top and run this code here to check its output. It will show an error − First number: 20 Second number: 10PHP Fatal error: Uncaught TypeError: division(): Return value must be of type int, float returned in /home/cg/root/14246/main.php:5 Stack trace: #0 /home/cg/root/14246/main.php(13): division() #1 {main} thrown in /home/cg/root/14246/main.php on line 5 Print Page Previous Next Advertisements ”;
PHP – Null Coalescing Operator ”; Previous Next The Null Coalescing operator is one of the many new features introduced in PHP 7. The word “coalescing” means uniting many things into one. This operator is used to replace the ternary operation in conjunction with the isset() function. Ternary Operator in PHP PHP has a ternary operator represented by the “?” symbol. The ternary operator compares a Boolean expression and executes the first operand if it is true, otherwise it executes the second operand. expr ? statement1 : statement2; Example Let us use the ternary operator to check if a certain variable is set or not with the help of the isset() function, which returns true if declared and false if not. <?php $x = 1; $var = isset($x) ? $x : “not set”; echo “The value of x is $var”; ?> It will produce the following output − The value of x is 1 Now, let”s remove the declaration of “x” and rerun the code − <?php # $x = 1; $var = isset($x) ? $x : “not set”; echo “The value of x is $var”; ?> The code will now produce the following output − The value of x is not set The Null Coalescing Operator The Null Coalescing Operator is represented by the “??” symbol. It acts as a convenient shortcut to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand. $Var = $operand1 ?? $operand2; The first operand checks whether a certain variable is null or not (or is set or not). If it is not null, the first operand is returned, else the second operand is returned. Example Take a look at the following example − <?php # $num = 10; $val = $num ?? 0; echo “The number is $val”; ?> It will produce the following output − The number is 0 Now uncomment the first statement that sets $num to 10 and rerun the code − <?php $num = 10; $val = $num ?? 0; echo “The number is $val”; ?> It will now produce the following output − The number is 10 A useful application of Null Coalescing operator is while checking whether a username has been provided by the client browser. Example The following code reads the name variable from the URL. If indeed there is a value for the name parameter in the URL, a Welcome message for him is displayed. However, if not, the user is called Guest. <?php $username = $_GET[”name”] ?? ”Guest”; echo “Welcome $username”; ?> Assuming that this script “hello.php” is in the htdocs folder of the PHP server, enter http://localhost/hello.php?name=Amar in the URL, the browser will show the following message − Welcome Amar If http://localhost/hello.php is the URL, the browser will show the following message − Welcome Guest The Null coalescing operator is used as a replacement for the ternary operator’s specific case of checking isset() function. Hence, the following statements give similar results − <?php $username = isset($_GET[”name”]) ? $_GET[”name”] : ”Guest”; echo “Welcome $username”; ?> It will now produce the following output − Welcome Guest You can chain the “??” operators as shown below − <?php $username = $_GET[”name”] ?? $_POST[”name”] ?? ”Guest”; echo “Welcome $username”; ?> It will now produce the following output − Welcome Guest This will set the username to Guest if the variable $name is not set either by GET or by POST method. Print Page Previous Next Advertisements ”;
PHP – Array Functions
PHP Array Functions ”; Previous Next PHP Array Functions allow you to interact with and manipulate arrays in various ways. PHP arrays are essential for storing, managing, and operating on sets of variables. PHP supports simple and multi-dimensional arrays and may be either user created or created by another function. Installation There is no installation needed to use PHP array functions; they are part of the PHP core and comes alongwith standard PHP installation. Runtime Configuration This extension has no configuration directives defined in php.ini. PHP Array Functions Following table lists down all the functions related to PHP Array. Here column version indicates the earliest version of PHP that supports the function. Sr.No Function & Description Version 1 array() Create an array 4.2.0 2 array_change_key_case() Returns an array with all keys in lowercase or uppercase 4.2.0 3 array_chunk() Splits an array into chunks of arrays 4.2.0 3 array_column() Return the values from a single column in the input array 5.5.0 4 array_combine() Creates an array by using one array for keys and another for its values 5 5 array_count_values() Returns an array with the number of occurrences for each value 4 6 array_diff() Compares array values, and returns the differences 4 7 array_diff_assoc() Compares array keys and values, and returns the differences 4 8 array_diff_key() Compares array keys, and returns the differences 5 9 array_diff_uassoc() Compares array keys and values, with an additional user-made function check, and returns the differences 5 10 array_diff_ukey() Compares array keys, with an additional user-made function check, and returns the differences 5 11 array_fill() Fills an array with values 4 12 array_fill_keys() Fill an array with values, specifying keys 5 13 array_filter() Filters elements of an array using a user-made function 4 14 array_flip() Exchanges all keys with their associated values in an array 4 15 array_intersect() Compares array values, and returns the matches 4 16 array_intersect_assoc() Compares array keys and values, and returns the matches 4 17 array_intersect_key() Compares array keys, and returns the matches 5 18 array_intersect_uassoc() Compares array keys and values, with an additional user-made function check, and returns the matches 5 19 array_intersect_ukey() Compares array keys, with an additional user-made function check, and returns the matches 5 20 array_key_exists() Checks if the specified key exists in the array 4 21 array_keys() Returns all the keys of an array 4 22 array_map() Sends each value of an array to a user-made function, which returns new values 4 23 array_merge() Merges one or more arrays into one array 4 24 array_merge_recursive() Merges one or more arrays into one array 4 25 array_multisort() Sorts multiple or multi-dimensional arrays 4 26 array_pad() Inserts a specified number of items, with a specified value, to an array 4 27 array_pop() Deletes the last element of an array 4 28 array_product() Calculates the product of the values in an array 5 29 array_push() Inserts one or more elements to the end of an array 4 30 array_rand() Returns one or more random keys from an array 4 31 array_reduce() Returns an array as a string, using a user-defined function 4 32 array_reverse() Returns an array in the reverse order 4 33 array_search() Searches an array for a given value and returns the key 4 34 array_shift() Removes the first element from an array, and returns the value of the removed element 4 35 array_slice() Returns selected parts of an array 4 36 array_splice() Removes and replaces specified elements of an array 4 37 array_sum() Returns the sum of the values in an array 4 38 array_udiff() Compares array values in a user-made function and returns an array 5 39 array_udiff_assoc() Compares array keys, and compares array values in a user-made function, and returns an array 5 40 array_udiff_uassoc() Compares array keys and array values in user-made functions, and returns an array 5 41 array_uintersect() Compares array values in a user-made function and returns an array 5 42 array_uintersect_assoc() Compares array keys, and compares array values in a user-made function, and returns an array 5 43 array_uintersect_uassoc() Compares array keys and array values in user-made functions, and returns an array 5 44 array_unique() Removes duplicate values from an array 4 45 array_unshift() Adds one or more elements to the beginning of an array 4 46 array_values() Returns all the values of an array 4 47 array_walk() Applies a user function to every member of an array 3 48 array_walk_recursive() Applies a user function recursively to every member of an array 5 49 arsort() Sorts an array in reverse order and maintain index association 3 50 asort() Sorts an array and maintain index association 3 51 compact() Create array containing variables and their values 4 52 count() Counts elements in an array, or properties in an object 3 53 current() Returns the current element in an array 3 54 each() Returns the current key and value pair from an array 3 55 end() Sets the internal pointer of an array to its last element 3 56 extract() Imports variables into the current symbol table from an array 3 57 in_array() Checks if a specified value exists in an array 4 58 key() Fetches a key from an array 3 59 krsort() Sorts an array by key in reverse order 3 60 ksort() Sorts an array by key 3 61 list() Assigns variables as if they were an array 3 62 natcasesort() Sorts an array using a case insensitive “natural order” algorithm 4 63 natsort() Sorts an array using a “natural order” algorithm 4 64 next() Advance the internal array pointer of an array 3 65 pos() Alias of current() 3 66 prev() Rewinds the internal array pointer 3 67 range() Creates an array containing a range of elements 3 68 reset() Sets the internal pointer of an array to its first element 3 69 rsort() Sorts an array in reverse order 3 70 shuffle() Shuffles an array 3 71 sizeof() Alias of count() 3 72 sort() Sorts an array 3 73 uasort() Sorts an array with
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 ”;