PHP Functions Flashcards

1
Q

Task: Replace a backslash with a forward slash

A

$string = str_replace(‘\’, ‘/’, $string);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Task: Determine if a given filename exists in the specified location

A
if (file_exists($filename)) {
  // do stuff
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Task: Use a function to filter a URL to make sure it’s safe

A

$url = filter_var($this->url, FILTER_SANITIZE_URL);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Task: Write a function to remove the whitespace off the ends of a string.

A

$str = trim($string);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Task: Given a string with colons as a separator, split the string up into components into an array.

A

$array = explode(“:”, $input);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Task: Determine if a string exists in an array of srings

A

if (in_array($string, $array)) { // Do stuff }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Task: Get all of the methods names from a class

A

$methods = get_class_methods($obj);
or
$methods = get_class_methods(‘className’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Task: Convert all strings in an array to lowercase

A

$yourArray = array_map(‘strtolower’, $yourArray);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Task: Sort an array that has keys, without damaging the keys

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Task: Sort an array - keys don’t matter

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Task: Make the first letter in a string uppercase

A

string ucfirst ( string $str );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Task: Format a decimal number into thousands for nice display

A

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 = “,” )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Task: Create a string from an array, that is separated by a ‘glue’ string

A

string implode ( string $glue , array $pieces );

glue could be ‘,’ to create a csv

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Task: Make the first characters of a string lowercase.

A

string lcfirst ( string $str )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Task: Compare two strings for equality

A

int strcmp ( string $str1 , string $str2 )

Returns 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Task: Parse a url, and return an associative array with it’s components

A

mixed parse_url ( string $url [, int $component = -1 ] );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Task: Take a string and parse it like a URL, outputing the variable / value combinations into new variables

A

void parse_str ( string $str [, array &$arr ] )

NOTE: It does not return a value - it will write the values into new variables

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Question: What is the issue with using parse_str?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Task: Which function would you use to compare two strings and ensure it takes into account the current locale?

A

int strcoll ( string $str1 , string $str2 )

NOTE: Not binary safe

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Question: Which function is just an alias of implode?

A

join

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Task: You need to cut whitespace or other characters from the end of a string.

A

string rtrim ( string $str [, string $character_mask ] )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Question: What function is an alias of rtrim?

A

chop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Task: You have to parse a comma seperated string into an array?

A

array str_getcsv ( string $input [, string $delimiter = “,” [, string $enclosure = ‘”’ [, string $escape = “\” ]]] )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Question: What is the case insensitive version of str_replace?

A

str_ireplace

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
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 = "\\" ]]]] )
26
Question: What needs to be done before fgetcsv can be used?
A file must be opened using fopen (it requires a file handle)
27
Task: Convert data to a JSON format
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
28
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)
29
Question: What does the JSON_FORCE_OBJECT bitmask do?
It encodes the array as an object
30
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)
31
Task: Use a function to decode a string of JSON
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
32
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
33
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
34
Task: Use a function to determine what the last error was from a json decode or encode
int json_last_error ( void )
35
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));
36
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 ] )
37
Task: Remove and return the start of the array (i.e. element 0)
mixed array_shift ( array &$array )
38
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.
39
Task: Obtain a backtrace for debugging purposes
array debug_backtrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT [, int $limit = 0 ]] )
40
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).
41
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.
42
Task: Determine, in a single function call whether a method is present on an object?
bool method_exists ( mixed $object , string $method_name )
43
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.
44
Task: Start a session in PHP
bool session_start ( void )
45
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. )
46
Task: Get the session id
string session_id ([ string $id ] )
47
Question: What function would you use to test if a session already exists?
session_id() == ''
48
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
49
Task: You need to generate a hash for a password - what should you use?
string password_hash ( string $password , integer $algo [, array $options ] )
50
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.
51
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 ]]]]]] )
52
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)
53
Task: Convert a string into a value safe for making part of a url
string urlencode ( string $str )
54
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)
55
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');
56
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 ]]] )
57
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 ```
58
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)
59
Task: Find the first occurrance of a substring in a string.
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
60
Task: Remove any null elements from an array
array array_filter ( array $array [, callable $callback ] )
61
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.
62
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.
63
Question: What is an anonymous function?
A function without a name
64
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)
65
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); } ```
66
Task: Apply a function (closure or lamdba) to each element in an array
bool array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] )
67
Question: What kind of type hinting can be used to ensure a variable passed to a function is a lambda / closure?
callable
68
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']) ```
69
Task: Read a file and write contents into an array
array file ( string $filename [, int $flags = 0 [, resource $context ]] )
70
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()
71
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 ]]]] )
72
Task: Initialise a curl handle
resource curl_init ([ string $url = NULL ] ) i.e. $cur = curl_init();
73
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.
74
Task: Determine the similarity between two strings
int similar_text ( string $first , string $second [, float &$percent ] )
75
Question: What does PCRE stand for?
Perl Compatible Regular Expressions
76
Question: What prefix do functions in PHP that deal with PCRE start with?
preg | I.e. preg_match - reg ex
77
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 ]]] )
78
Task: Split a string at the point where a regex matches
array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
79
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
80
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.
81
Task: Encode an image appropriately for storing in a database
string base64_encode ( string $data )
82
Task: Determine the name of a file given a path
string basename ( string $path [, string $suffix ] )
83
Task: Determine the date / time of the last file modification?
int filemtime ( string $filename )
84
Task: Reset an arrays internal pointer to the first element.
mixed reset ( array &$array ) NOTE: Reset will return the first element in the aray
85
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 ] )
86
Task: Sort an array by key in reverse
bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
87
Task: Sum an array containing numerical elements?
number array_sum ( array $array )
88
Task: Test for a scalar variable?
bool is_scalar ( mixed $var )
89
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);
90
Task: Take an array and randomise the elements within it.
bool shuffle ( array &$array )
91
Task: Split a string either into characters or at a specific point in a string
array str_split ( string $string [, int $split_length = 1 ] )
92
Task: Decompress a gzip'd file
string gzuncompress ( string $data [, int $length = 0 ] )