php tagged requests and articles

Categorized request examples and articles tagged with [php] keyword
How do I send a POST request using PHP?
There are two ways to send POST requests from PHP: the built-in PHP Curl library and a non-CURL method using PHP's native streaming features. The PHP Curl library gives you full control over sending the request but requires additional initialization steps, while the CURL-less method is easier to use but has limited capabilities. In this PHP POST request example, we are sending a POST request using the PHP Curl library. The CURL-less method is provided with detailed explanations at the end of the article. Click Execute to run the PHP POST Request Example online and see the result.

How to check if a string contains a substring in PHP?
To check if a PHP string contains a substring, you can use the strpos($string, $substring) function. If the string contains the searched substring, the strpos() function will return the index of the first occurrence of the substring in the string; otherwise "false". In PHP, indexes start at 0. As of PHP 8+, you can use the new str_contains($string, $substring) function to check if a string contains the desired substring or word. The str_contains() function returns "true" if the string contains a substring or "false" otherwise. Also, you can use Regular Expressions to check if a PHP string contains a substring. Regular Expressions, unlike other methods, provide more flexibility but are slower. In this PHP String Contains Substring example, we use the strpos() function to check if the string contains a substring. Click Execute to run the PHP String Contains example online and see the result.

How do I POST JSON using PHP Curl Library?
To post JSON to the server using the PHP Curl library, you first need to initialize the Curl library by calling the curl_init() function and then pass request parameters using the curl_setopt() function. To pass the target URL, use the CURLOPT_URL parameter, and for the request headers, use the CURLOPT_HTTPHEADER parameter. The JSON data can be passed to the request using the CURLOPT_POSTFIELDS parameter. In this PHP Curl POST JSON example, we post JSON to the ReqBin echo URL with additional Accept and Content-Type headers. Click Execute to run the PHP Curl POST JSON Example online and see the result.

How do I convert JSON to PHP array?
To convert a JSON data string to a PHP array, you can use the json_decode($json) function. The json_decode() function accepts the JSON string as the first parameter and a few additional parameters to control the process of converting JSON to a PHP array. If the JSON cannot be converted to an array or the data nesting depth exceeds the recursion limit, the converting function will return NULL. In this JSON Convert to PHP Array example, we use the json_decode() function to convert JSON string to a PHP array. Click Execute to run the JSON to PHP Array Example online and see the result.

How do I convert PHP Array to JSON?
To convert a PHP array to JSON data string, you can use the json_encode($value, $flags, $depth) function. The json_encode() function takes a PHP array as input and returns a JSON string representation. You can customize the conversion of a PHP array to JSON using additional parameters for the json_encode() function, such as "JSON_PRETTY_PRINT", for human-readable formatting and JSON output behavior. In this PHP Array to JSON example, we use the json_encode() function to convert a PHP array to a JSON string with no additional parameters. Below, you'll find more examples demonstrating additional options for converting a PHP array to a JSON string. Click Execute to run the Convert PHP Array to JSON String Example online and see the result.

How do I print an array in PHP?
To print or echo an array in PHP, you can use the print_r($variable, $return) or var_dump($variable1, $variable2, ...) functions. The print_r() function prints information about the passed variable in human-readable form. The first parameter is the "variable" we want to get information about. The second optional parameter determines whether the function should print or return the result. The default value is "False". If the parameter value is "True", the function will return the value as if it were printed to the output stream. The var_dump() function takes one or more arguments and displays structured information about the variables, including the type and value. In this Print PHP Array example, we use the print_r() function to print information about a given array. Below you can see more examples of PHP array printouts with a detailed description of each method. Click Execute to run the PHP Print Array Example online and see the result.

How do I convert a string to int in PHP?
The easiest way to convert strings to numbers in PHP is to use the (int/float/double)$variable cast, which directly converts the string to a number. You can also convert a string to a number using the intval($value, $base), floatval($value), number_format($num, $decimals) and settype($var, $type) functions. The intval() function converts a string to an integer, and the floatval() function converts a string to a floating-point value. The number_format() function converts a string to a number and returns the formatted number on success; if it fails, the function throws an E_WARNING error. The settype() function is used to set or change the type of an existing variable. In this PHP String to Int example, we convert a string to a number using the intval() function. Below you can see more string-to-int conversion examples with detailed descriptions of each method. Click Execute to run the PHP String to Int Example online and see the result.

How to post form data in PHP?
To post form data in PHP, you can use the built-in PHP Curl library. You need to initialize the PHP Curl library first by calling the curl_init() function. You can pass the target URL during initialization or set it later by calling the curl_setopt() function with the "CURLOPT_URL" parameter. To pass additional HTTP headers to a PHP POST HTML form request, you can call curl_setopt() with the "CURLOPT_HTTPHEADER" parameter. In this PHP Form POST example, we are sending HTML form data to the ReqBin echo URL and specifying the data type in the POST message with the "Content-Type: application/x-www-form-urlencoded" request HTTP header. Click Execute to run the PHP Post Form Example online and see the result.

How do I split a string in PHP?
To split a string into an array in PHP, you can use the explode($separator, $string, $limit) function. The explode() is a built-in function that splits strings into arrays. The function takes three parameters: an input string to split, a delimiter, and, optionally, a limit on the number of array elements. The explode() function converts a string to an array, separating the given string with a delimiter. Both separator and string are required. The optional parameter "limit" specifies the number of array elements to return. In this PHP Split String example, we split a string into an array using the explode() function. Below you can see more examples of splitting strings in PHP with a detailed description of each method. Click Execute to run the PHP Split String to Array Example online and see the result.

How do I compare strings in PHP?
The easiest way to compare PHP strings is to use the logical operators ('==') and ('!='). If you want to know which string is lexicographically greater or lesser, you can use the operators ('<'), ('>'), ('<='), ('>='). You can also compare strings using the strcmp($string1, $string2) and strcasecmp($string1, $string2) functions. The strcmp() function is a case-sensitive safe binary string comparison function that returns 0 if the strings match. The strcasecmp() function is similar but performs a case-insensitive comparison. In this PHP String Compare example, we compare strings using the ("==") operator. Click Execute to run the PHP Compare Strings Example online and see the result.

How do I send a GET request using PHP?
To make an HTTP GET request with PHP, you can use the PHP Curl library or the built-in PHP streaming functions. The Curl-based method is preferred when you need to send additional HTTP headers to the server with your GET request, limit download speed, or diagnose request errors, while PHP's built-in streaming functions are less verbose and easier to use. In this PHP GET Request Example, we send a GET request using the PHP-Curl library. The Curl-less method is provided below with detailed description. Click Execute to run the PHP GET Request Example online and see the result.

How do I convert string to lowercase in PHP?
To convert a string to lowercase in PHP, you can use the strtolower($string) function. The strtolower() function takes a string as a parameter and converts all uppercase English characters to lowercase. To convert non-English characters to lowercase, you can use the mb_strtolower() function. All other numeric characters or special characters in the string are left unchanged. In this PHP String to Lowercase example, we convert a string to lowercase using the strtolower() function. Click Execute to run the PHP Lowercase String Example online and see the result.

How do I encode a PHP object to JSON string?
To encode a PHP object to a JSON formatted string, you can use the json_encode($value, $options, $depth) function. The $value parameter specifies the PHP object to encode. The additional $options parameter provides additional options for JSON encoding. You can control how the PHP object will be encoded into JSON by passing a combination of bitmasks. See the list of supported bitmasks for JSON encoding below. The third optional parameter specifies the maximum recursion depth, in other words, how deep the encoding function will go through the nested PHP objects and convert them to JSON. In this PHP Encode JSON example, we use the json_encode() function to encode a PHP object into its JSON representation. Click Execute to run the PHP JSON Encode Example online and see the result.

How to check if an element exists in a PHP array?
To check if an element exists in a PHP array, you can use the in_array($search, $array, $mode) function. The $search parameter specifies the element or value to search in the specified array and can be of a mixed type (string, integer, or other types). If the parameter is a string type, the search will be case-sensitive. The $array parameter specifies the array to search for the value. The $mode parameter is an optional boolean parameter that specifies the search mode. If the parameter is set to TRUE, then the in_array() function will search for a value with the same value type as specified in the "search" parameter. The default value for the "mode" parameter is FALSE. In this PHP Search In Array example, we use the in_array() function to check whether the given value exists in the array. Click Execute to run the PHP In Array Example online and see the result.

How to get a substring from a string in PHP?
To get a substring from a string in PHP, you can use the built-in substr($string, $offset, $length) function. The $offset indicates the position at which substr() starts extracting the substring, and the optional $length parameter specifies how many characters to return, starting at offset. In PHP, indexing starts at 0. A negative value means that substr() will return a substring beginning at an $offset from the end of the string. If the optional $length parameter is passed, substr() will return the specified number of characters. If $length is negative, then the specified number of characters will be omitted at the end of the string. In this PHP Substr Example, we extract the first three characters from a string. Click Execute to run the PHP substr() function online and see the result.

How do I parse JSON string in PHP?
To parse a JSON string to a PHP object or array, you can use the json_decode($json) function. The json_decode() function recursively converts the passed JSON string into the corresponding PHP objects. You can control the parsing flow by passing a set of bitmasks to the JSON decoder function. If the JSON cannot be parsed or the nested JSON data has a depth greater than the recursion limit, the json_decode() returns NULL. The PHP JSON parser only works with UTF-8 encoded strings. To encode PHP objects to JSON string, you can use json_encode($value) function. In this PHP JSON Parse example, we use the json_decode() function to decode JSON strings into PHP objects. Click Execute to run the PHP Parse JSON Example online and see the result.

How do I concatenate strings in PHP?
To concatenate strings in PHP, you can use the concatenation operator (' . ') and the concatenate assignment operator (' .= '). The concatenation operator (' . ') returns the concatenation result of the right and left arguments. When concatenating, each subsequent line is added to the end of the previous one. A value of any type that is concatenated with a string will be implicitly converted to a string and then concatenated. The assignment operator (' .= ') adds the argument on the right side to the argument on the left side. This is a shorter way to concatenate the arguments and assign the result to the same variable. In this PHP String Concatenation example, we use the concatenation operator (' . ') and return the concatenating arguments. Click Execute to run the PHP Concatenation String Example online and see the result.

How do I interpolate strings in PHP?
To interpolate a string in PHP, you need to enclose the string literals in double quotes and include variables in the string, starting with $. In PHP, string interpolation only works with double-quoted strings. If single quotes are used in the string, then the variable's value is not interpolated, and the string will be printed as-is. In this PHP String Interpolation example, we use interpolation to format a string using several variables. Click Execute to run the PHP String Interpolation Example online and see the result.

How do I convert an array to a string in PHP?
To convert an array to a string in PHP you can use implode($separator, $array), json_encode($array) or serialize($array) functions. The implode() function allows you to concatenate array elements into a single string. To do this, pass an array, and a delimiter to the implode(); the separator will be inserted between the array values. The json_encode() function converts an array to a JSON string. It takes an array as input and returns a JSON array representation. The serialize() function takes an array and converts it to a string. This function is handy if you want to store something in the database and retrieve it for later use. In this Convert PHP Array to String example, we use the implode() function to convert an array to a string. Below you can see more examples of converting a PHP array to a string with a detailed description of each method. Click Execute to run the PHP Array to String Example online and see the result.

How to push an element into a PHP array?
To add elements to a PHP array, you can use the array_push($array, $val1, $val2, ....) function. The array_push() function adds one or more elements to the end of the array and automatically increases the array's length. The $array parameter refers to the original array to which elements are added. The function will raise an exception if the first argument is not an array. The parameters $val1 and $val2 are the elements we want to push into the array. In this PHP Push Elements to Array example, we add elements to an array using the array_push() function. Click Execute to run the PHP Array Push Example online and see the result.

How to create a new array using PHP array_map()?
To create a new array from an existing PHP array, you can use the array_map($callback, $array1, $array2, ...) function. The array_map() function iterates over all the elements of an array and returns a new array containing the results of applying the given $callback function to the array elements. The array_map() function does not change the original array but creates a new one. You can pass several arrays to the array_map() function. The number of parameters the $callback function takes must match the number of arrays passed to the array_map(). The first parameter can be a string representing the function name, an array containing an object and a method name, or an anonymous function. The second parameter specifies the array to process. In this PHP Array Map example, we use the array_map() function to loop over an array and return a new array, where a callback function has been applied to each element in the array. Click Execute to run the PHP Array Map Example online and see the result.

How can I get the length of a string in PHP?
To get the length of a string in PHP, use the strlen($string) built-in function. The strlen() takes a string as an argument and returns the length of the string. The strlen() function returns the number of bytes, not characters. If your string contains Unicode characters, strlen() will return a string length bigger than the number of visible characters since Unicode characters are represented in PHP as 2 bytes. To get the number of visible characters, use the mb_strlen($string, 'utf8') function instead of strlen(). Recent versions of PHP have significantly improved the performance of the strlen() function. Multiple strlen() calls for long PHP strings are almost as fast as a single call. In this PHP String Length example, we use the strlen() function to get the length of an ASCII string (without Unicode characters). Click Execute to run the PHP String Length example online and see the result.

How to get the length of an array in PHP?
To get the array's length in PHP, you can use the count() and sizeof() functions that return the number of items in the array. Function sizeof() is the alias of the count() function. The count() function returns 0 for a variable initialized by an empty array. In this PHP Array Length example, we obtain the array's length using the count() function. Click Execute to run the PHP Array Length Example online and see the result.

How do I decode JSON in PHP?
To decode a JSON string or file in PHP, you can use the json_decode($json, $assoc, $depth, $options) function. The first parameter specifies the string to be decoded. The second optional parameter sets whether the returned object should be converted to an associative array. By default, the json_decode() function recursively decodes JSON with a depth of 512. You can set a different recursion depth in the third parameter. If the JSON cannot be decoded or the nesting depth of the data is greater than the recursion limit, the decode function will return NULL. To encode PHP objects to JSON, you can use the json_encode($value) function. In this PHP Decode JSON example, we use the json_decode() function to convert a JSON string into a PHP object using default values. Click Execute to run the PHP JSON Decode Example online and see the result.

How do I replace a string in PHP?
To replace a string with a substring in PHP, use the str_replace($search, $replace, $subject, $count) function. The str_replace() function takes the string to search for as the first argument, the string to replace the old value with as the second argument, and the string where the replacement is to take place as the third argument. The str_replace() function does not modify the original string; instead, it returns a copy of the replaced string. If the optional argument $count is passed, it will contain the number of replacements performed. You can pass arrays to the $search, and $replace to perform multiple replacements simultaneously. You can also replace strings with PHP Regular Expressions (see example below). In this PHP string replacement example, we replace all occurrences of the search string with a substring using the str_replace() function. Click Execute to run the PHP String Replace Example online and see the result.

How do I sort an array in PHP?
To sort the elements of a PHP array, you can use one of the following PHP functions: sort(), rsort(), asort(), ksort(), arsort(), krsort(). Arrays can be sorted alphabetically or numerically, in ascending or descending order. When sorting an associative array in PHP, array keys retain their correlation with the associated values. The sort() function sorts an array in ascending order, while rsort() sorts it in descending order. The asort() function sorts an associative array in ascending order, and the arsort() sorts in descending order. The ksort() function sorts associative arrays in ascending order by keys, and the krsort() sorts in descending order. In this PHP Sort Array example, we use the sort() function to sort the elements of an array in numerical order. Below you can see more examples of sorting PHP array elements with a detailed description of each method. Click Execute to run the PHP Sort Array Example online and see the result.

How to Parse XML in PHP?
To parse XML in PHP, you can to use the SimpleXML extension. The SimpleXML is an extension allowing us to easily manipulate and retrieve data from XML strings. The SimpleXML turns XML into a data structure that can be iterated over like a collection of arrays and objects. As of PHP 5, the SimpleXML functions are part of the PHP core, and no installation is required to use them. In this PHP Parse XML example, we use the simplexml_load_string method, which provides a convenient way to access XML content. You can find more examples of parsing XML in PHP below. Click Execute to run the PHP Parse XML Example online and see the result.

How to assign multiple variables at once in PHP using list()?
The list() construct in PHP assigns multiple variables at once using an array. This is especially useful when splitting an array into individual variables. As of PHP 7.1, the list() supports square bracket [] syntax. For list() to work correctly, the number of variables you are trying to assign must match the number of elements in the array. The remaining variables will be ignored if there are fewer variables than array elements. The additional variables will be set to NULL if there are more variables than array elements. The list() construct only supports indexed arrays and does not work with associative arrays. For associative arrays, you need to extract the values first. In this PHP List Example, we assign multiple variables at once using the list() construct. Click Execute to run the PHP List Example online and see the result.

How to delay execution of a script in PHP using sleep()?
The PHP sleep() function pauses script execution for a specified number of seconds. The sleep() function takes only one argument, which specifies how long to pause the script. The primary purpose of using the PHP sleep() function is to debug and troubleshoot code and simulate long-running tasks or requests. Using the sleep() function on production servers is not recommended due to the potential risk of reducing web application performance. In this PHP Sleep Example, we pause the execution of a script for a specified number of seconds using the sleep() function. Click Execute to run the PHP Sleep Example online and see the result.

How to print variables in PHP using print_r?
The print_r function in PHP allows you to print the contents of variables, arrays, and objects in a human-readable format. Primary print_r is used for debugging since it lets you visually inspect data structures' contents. To use print_r, pass the variable you want to inspect as the first argument to the function. If you want the output returned as a string rather than printed to the screen, specify true as the second argument to the function. In this PHP print_r example, we print the contents of a variable on the screen and save it to a string. Click Execute to run the PHP print_r example online and see the result.

How to concatenate array elements in PHP using implode() function?
PHP's built-in implode() function concatenates array elements into a string using a specified delimiter. It returns a string resulting from joining the array elements separated by the provided string. To use the implode() function, you should pass two arguments: the string you want to use as the delimiter and the array you want to concatenate. If you pass only one argument (an array), PHP will automatically use the empty string as the delimiter. The implode() function does not change the original array. In this PHP Implode Example, we concatenate array elements using a comma as a separator. Click Execute to run the PHP Implode Example online and see the result.

How to execute code conditionally in PHP using the switch statement?
The "switch" statement in PHP is a conditional statement that allows you to execute one block of code from various alternatives. Instead of using a long chain of "if", "else if", and "else" statements, you can use just one "switch". The "switch" statement makes your code more readable and maintainable. The keyword "case" is used to specify each possible alternative and the "default" keyword is used to specify the code that should be executed if none of the conditions are met. Each "case" must end with a "break" statement to avoid potential errors. For the "default", the "break" statement is not required but is recommended. In this PHP Switch Example, we execute code blocks conditionally using the switch statement. Click Execute to run the PHP Switch Example online and see the result.

How to use if-else statement in PHP?
The PHP if-else statement executes specific blocks of code depending on whether a given condition is true or false. If the condition is true, the code block will be executed immediately following the condition, enclosed in curly braces {}. If the condition is false and there is an "else" statement after the "if", the block of code associated with the "else" condition will be executed. PHP also offers the "elseif" statement, which can be used between "if" and "else" to test multiple conditions sequentially. The associated code block is executed once a condition returns true, and the rest are skipped. It's important to remember that "if", "else", and "elseif" blocks are mutually exclusive, meaning only one block of code will be executed depending on which condition is met first. In this PHP if-else example, we execute a certain block of code based on the specified condition. Click Execute to run the PHP if-else example online and see the result.