PHP Functions Flashcards
Task: Replace a backslash with a forward slash
$string = str_replace(‘\’, ‘/’, $string);
Task: Determine if a given filename exists in the specified location
if (file_exists($filename)) { // do stuff }
Task: Use a function to filter a URL to make sure it’s safe
$url = filter_var($this->url, FILTER_SANITIZE_URL);
Task: Write a function to remove the whitespace off the ends of a string.
$str = trim($string);
Task: Given a string with colons as a separator, split the string up into components into an array.
$array = explode(“:”, $input);
Task: Determine if a string exists in an array of srings
if (in_array($string, $array)) { // Do stuff }
Task: Get all of the methods names from a class
$methods = get_class_methods($obj);
or
$methods = get_class_methods(‘className’);
Task: Convert all strings in an array to lowercase
$yourArray = array_map(‘strtolower’, $yourArray);
Task: Sort an array that has keys, without damaging the keys
bool uasort ( array &$array , callable $value_compare_func )
NOTE: $value_compare_func should do a test between the two values and return -1 or 1 (not much point in returning 0)
Task: Sort an array - keys don’t matter
bool usort ( array &$array , callable $value_compare_func );
NOTE: $value_compare_func should test between two values and return -1 or 1 (not much point in returning 0)
Task: Make the first letter in a string uppercase
string ucfirst ( string $str );
Task: Format a decimal number into thousands for nice display
string number_format ( float $number [, int $decimals = 0 ] );
OR (note: only 1,2 or 4 parameters allowed)
string number_format ( float $number , int $decimals = 0 , string $dec_point = “.” , string $thousands_sep = “,” )
Task: Create a string from an array, that is separated by a ‘glue’ string
string implode ( string $glue , array $pieces );
glue could be ‘,’ to create a csv
Task: Make the first characters of a string lowercase.
string lcfirst ( string $str )
Task: Compare two strings for equality
int strcmp ( string $str1 , string $str2 )
Returns 0
Task: Parse a url, and return an associative array with it’s components
mixed parse_url ( string $url [, int $component = -1 ] );
Task: Take a string and parse it like a URL, outputing the variable / value combinations into new variables
void parse_str ( string $str [, array &$arr ] )
NOTE: It does not return a value - it will write the values into new variables
Question: What is the issue with using parse_str?
If you don’t pass an array as the second argument, values are written to the current context, and could overwrite values. Using an array means they are written to the array
Task: Which function would you use to compare two strings and ensure it takes into account the current locale?
int strcoll ( string $str1 , string $str2 )
NOTE: Not binary safe
Question: Which function is just an alias of implode?
join
Task: You need to cut whitespace or other characters from the end of a string.
string rtrim ( string $str [, string $character_mask ] )
Question: What function is an alias of rtrim?
chop
Task: You have to parse a comma seperated string into an array?
array str_getcsv ( string $input [, string $delimiter = “,” [, string $enclosure = ‘”’ [, string $escape = “\” ]]] )
Question: What is the case insensitive version of str_replace?
str_ireplace
Task: read a single line of a file and write the contents into an array
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = “,” [, string $enclosure = ‘”’ [, string $escape = “\” ]]]] )
Question: What needs to be done before fgetcsv can be used?
A file must be opened using fopen (it requires a file handle)
Task: Convert data to a JSON format
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
Question: What does the JSON_NUMERIC_CHECK bitmask do?
Checks for a string being a number, if so will encode it as a number (so not as a string)
Question: What does the JSON_FORCE_OBJECT bitmask do?
It encodes the array as an object
Question: What does JSON_PRETTY_PRINT do?
It formats the output of json_encode in an easy to read manner (useful really only for debugging since it adds overhead)
Task: Use a function to decode a string of JSON
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
Question: What parameter do you set on json_decode to return an associative array instead of an object?
The second parameter should be set to true
Question: If a document is 3 levels deep, and you specify a max of 2 levels of recursion - what is returned, the first two levels or null?
null
Task: Use a function to determine what the last error was from a json decode or encode
int json_last_error ( void )
Task: The datasource is not under your control and you want to make sure the output of json_encode is UTF-8 compliant (or you will raise a JSON_ERROR_UTF8 when decoding) What function do you use to ensure UTF-8 encoding?
string utf8_encode ( string $data )’
utf8_encode(json_encode($payload));
Task: Use a built in php function to configure an error handler function.
mixed set_error_handler ( callable $error_handler [, int $error_types = E_ALL | E_STRICT ] )
Task: Remove and return the start of the array (i.e. element 0)
mixed array_shift ( array &$array )
Question: What operator should you use to test the return value of file_get_contents
the === operator. This is because it may return boolean false, but may also return a value that evaluates to false.
Task: Obtain a backtrace for debugging purposes
array debug_backtrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT [, int $limit = 0 ]] )
Task: Use php’s own logging system to write an error to the logs.
bool error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] )
NOTE: You can use message_type=1 to send an email, you would then need to provide extra_headers (just like PHP’s mail function).
Question: Can you use multiple autoloaders?
Yes - PHP will allow multiple autoloaders to be registered. When one fails to find a file, then it tries the next - therefore do NOT throw an error in an autoloader.
Task: Determine, in a single function call whether a method is present on an object?
bool method_exists ( mixed $object , string $method_name )
Question: If you use method_exists, and the class you pass to it doesn’t happen, will it use the autoloader?
Yes, it will use any registered auto loaders to find the class referenced.
Task: Start a session in PHP
bool session_start ( void )
Task: Log a user out of a session
bool session_destroy(void)
(NOTE: This doesn’t actually log the user out - it’s a step in the process. You also have to unset variables associated with the session and delete any cookies, and unset the session id. )
Task: Get the session id
string session_id ([ string $id ] )
Question: What function would you use to test if a session already exists?
session_id() == ‘’
Task: You have a hashed password, and you want to verify that a string entered by a user matches, what function do you use?
boolean password_verify ( string $password , string $hash )
NOTE: The hash should have been created using password_hash
Task: You need to generate a hash for a password - what should you use?
string password_hash ( string $password , integer $algo [, array $options ] )
Question: In the past it was common practise to provide a salt when creating hashed passwords. Should you do this when using password_hash?
No - the intended (and safest) mode of operation is to use password_hash with the default salt.
Task: You need to set a cookie
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Question: What is the main catch when using setcookie?
The data must be sent prior to ANY output from your page (including html and head tags)
Task: Convert a string into a value safe for making part of a url
string urlencode ( string $str )
Task: Validate that the domain of an email address is valid
bool checkdnsrr ( string $host [, string $type = “MX” ] )
NOTE: This function takes other ‘type’s’, such as A, MX, NS, SOA, PTR, CNAME, AAAA etc (basically dns record types)
Question: What is the issue with simply relying on the result of checkdnsrr?
Some domains can have special characters in them (especially ones in Europe) - you need to convert the domain to ascii first.
checkdnsrr(idn_to_ascii(‘ñandu.cl’), ‘A’);
Task: Convert a domain name to idna ascii form
string idn_to_ascii ( string $domain [, int $options = 0 [, int $variant = INTL_IDNA_VARIANT_2003 [, array &$idna_info ]]] )
Task: How would you determine if magic quotes was enabled on your system?
bool get_magic_quotes_gpc ( void ) NOTE: Always returns false as of PHP 5.4.0
Task: Find the last occurrence of a substring in a string.
int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )
(NOTE: The double rr in strrpos)
Task: Find the first occurrance of a substring in a string.
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
Task: Remove any null elements from an array
array array_filter ( array $array [, callable $callback ] )
Question: The function includes returns a value, what is it, and how do you make it return something more useful?
It returns 1 if the include was successful, however, if the file has a return statement in it, it will return that value.
Question: What is a lambda?
It is an anonymous function that can be assigned to a variable or passed to another function as an argument. It is useful for callbacks, and when we don’t want to create a function that is used only once and pollutes the global namespace.
Question: What is an anonymous function?
A function without a name
Question: What is the difference between a lambda and a closure?
They are essentially the same, however a closure can access variables outside the scope of the function (via the ‘use’ keyword)
Question: What is the test for a closure in PHP (i.e. how do we tell if it is indeed a closure?)
If it is an object, and it is callable (closures are objects in PHP and they implement __invoke)
function is_closure($t) { return is_object($t) && ($t instanceof Closure); }
Task: Apply a function (closure or lamdba) to each element in an array
bool array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] )
Question: What kind of type hinting can be used to ensure a variable passed to a function is a lambda / closure?
callable
Task: Create a stream context
resource stream_context_create ([ array $options [, array $params ]] ) NOTE: Options must be an associative array of arrays (i.e. $arr['wrapper']['options'])
Task: Read a file and write contents into an array
array file ( string $filename [, int $flags = 0 [, resource $context ]] )
Question: file will read the contents of a file into an array, what function would you use to write a file into a string?
file_get_contents()
Task: Read a file into a string
string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
Task: Initialise a curl handle
resource curl_init ([ string $url = NULL ] )
i.e. $cur = curl_init();
Task: set the options on curl handle
bool curl_setopt ( resource $ch , int $option , mixed $value )
NOTE: You may have to call this multiple times to set multiple options.
Task: Determine the similarity between two strings
int similar_text ( string $first , string $second [, float &$percent ] )
Question: What does PCRE stand for?
Perl Compatible Regular Expressions
Question: What prefix do functions in PHP that deal with PCRE start with?
preg
I.e. preg_match - reg ex
Task: Determine whether a string matches a given regex pattern
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
Task: Split a string at the point where a regex matches
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
Question: preg_split splits a string using a regex, is the pattern included in the output?
No - if the pattern is a straight work for example, (‘i.e. “is”’) - the strings either side will be returned, but not the pattern itself
Question: What is the difference between preg_match and preg_match_all?
preg_match_all will return (through the array) all of the matches, not just the first.
Task: Encode an image appropriately for storing in a database
string base64_encode ( string $data )
Task: Determine the name of a file given a path
string basename ( string $path [, string $suffix ] )
Task: Determine the date / time of the last file modification?
int filemtime ( string $filename )
Task: Reset an arrays internal pointer to the first element.
mixed reset ( array &$array )
NOTE: Reset will return the first element in the aray
Task: Run a function over each element in an array in a recursive function
bool array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] )
Task: Sort an array by key in reverse
bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Task: Sum an array containing numerical elements?
number array_sum ( array $array )
Task: Test for a scalar variable?
bool is_scalar ( mixed $var )
Task: Create an array with numbers between 4 and 16 that are divisible by 4 (in one function, no control statements)
array range ( mixed $start , mixed $end [, number $step = 1 ] )
range(4,16,4);
Task: Take an array and randomise the elements within it.
bool shuffle ( array &$array )
Task: Split a string either into characters or at a specific point in a string
array str_split ( string $string [, int $split_length = 1 ] )
Task: Decompress a gzip’d file
string gzuncompress ( string $data [, int $length = 0 ] )