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
Q

Task: read a single line of a file and write the contents into an array

A

array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = “,” [, string $enclosure = ‘”’ [, string $escape = “\” ]]]] )

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

Question: What needs to be done before fgetcsv can be used?

A

A file must be opened using fopen (it requires a file handle)

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

Task: Convert data to a JSON format

A

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

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

Question: What does the JSON_NUMERIC_CHECK bitmask do?

A

Checks for a string being a number, if so will encode it as a number (so not as a string)

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

Question: What does the JSON_FORCE_OBJECT bitmask do?

A

It encodes the array as an object

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

Question: What does JSON_PRETTY_PRINT do?

A

It formats the output of json_encode in an easy to read manner (useful really only for debugging since it adds overhead)

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

Task: Use a function to decode a string of JSON

A

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

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

Question: What parameter do you set on json_decode to return an associative array instead of an object?

A

The second parameter should be set to true

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

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?

A

null

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

Task: Use a function to determine what the last error was from a json decode or encode

A

int json_last_error ( void )

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

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?

A

string utf8_encode ( string $data )’

utf8_encode(json_encode($payload));

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

Task: Use a built in php function to configure an error handler function.

A

mixed set_error_handler ( callable $error_handler [, int $error_types = E_ALL | E_STRICT ] )

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

Task: Remove and return the start of the array (i.e. element 0)

A

mixed array_shift ( array &$array )

38
Q

Question: What operator should you use to test the return value of file_get_contents

A

the === operator. This is because it may return boolean false, but may also return a value that evaluates to false.

39
Q

Task: Obtain a backtrace for debugging purposes

A

array debug_backtrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT [, int $limit = 0 ]] )

40
Q

Task: Use php’s own logging system to write an error to the logs.

A

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
Q

Question: Can you use multiple autoloaders?

A

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
Q

Task: Determine, in a single function call whether a method is present on an object?

A

bool method_exists ( mixed $object , string $method_name )

43
Q

Question: If you use method_exists, and the class you pass to it doesn’t happen, will it use the autoloader?

A

Yes, it will use any registered auto loaders to find the class referenced.

44
Q

Task: Start a session in PHP

A

bool session_start ( void )

45
Q

Task: Log a user out of a session

A

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
Q

Task: Get the session id

A

string session_id ([ string $id ] )

47
Q

Question: What function would you use to test if a session already exists?

A

session_id() == ‘’

48
Q

Task: You have a hashed password, and you want to verify that a string entered by a user matches, what function do you use?

A

boolean password_verify ( string $password , string $hash )

NOTE: The hash should have been created using password_hash

49
Q

Task: You need to generate a hash for a password - what should you use?

A

string password_hash ( string $password , integer $algo [, array $options ] )

50
Q

Question: In the past it was common practise to provide a salt when creating hashed passwords. Should you do this when using password_hash?

A

No - the intended (and safest) mode of operation is to use password_hash with the default salt.

51
Q

Task: You need to set a cookie

A

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

52
Q

Question: What is the main catch when using setcookie?

A

The data must be sent prior to ANY output from your page (including html and head tags)

53
Q

Task: Convert a string into a value safe for making part of a url

A

string urlencode ( string $str )

54
Q

Task: Validate that the domain of an email address is valid

A

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
Q

Question: What is the issue with simply relying on the result of checkdnsrr?

A

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
Q

Task: Convert a domain name to idna ascii form

A

string idn_to_ascii ( string $domain [, int $options = 0 [, int $variant = INTL_IDNA_VARIANT_2003 [, array &$idna_info ]]] )

57
Q

Task: How would you determine if magic quotes was enabled on your system?

A
bool get_magic_quotes_gpc ( void )
NOTE: Always returns false as of PHP 5.4.0
58
Q

Task: Find the last occurrence of a substring in a string.

A

int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

(NOTE: The double rr in strrpos)

59
Q

Task: Find the first occurrance of a substring in a string.

A

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

60
Q

Task: Remove any null elements from an array

A

array array_filter ( array $array [, callable $callback ] )

61
Q

Question: The function includes returns a value, what is it, and how do you make it return something more useful?

A

It returns 1 if the include was successful, however, if the file has a return statement in it, it will return that value.

62
Q

Question: What is a lambda?

A

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
Q

Question: What is an anonymous function?

A

A function without a name

64
Q

Question: What is the difference between a lambda and a closure?

A

They are essentially the same, however a closure can access variables outside the scope of the function (via the ‘use’ keyword)

65
Q

Question: What is the test for a closure in PHP (i.e. how do we tell if it is indeed a closure?)

A

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
Q

Task: Apply a function (closure or lamdba) to each element in an array

A

bool array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] )

67
Q

Question: What kind of type hinting can be used to ensure a variable passed to a function is a lambda / closure?

A

callable

68
Q

Task: Create a stream context

A
resource stream_context_create ([ array $options [, array $params ]] )
NOTE: Options must be an associative array of arrays (i.e. $arr['wrapper']['options'])
69
Q

Task: Read a file and write contents into an array

A

array file ( string $filename [, int $flags = 0 [, resource $context ]] )

70
Q

Question: file will read the contents of a file into an array, what function would you use to write a file into a string?

A

file_get_contents()

71
Q

Task: Read a file into a string

A

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

72
Q

Task: Initialise a curl handle

A

resource curl_init ([ string $url = NULL ] )

i.e. $cur = curl_init();

73
Q

Task: set the options on curl handle

A

bool curl_setopt ( resource $ch , int $option , mixed $value )

NOTE: You may have to call this multiple times to set multiple options.

74
Q

Task: Determine the similarity between two strings

A

int similar_text ( string $first , string $second [, float &$percent ] )

75
Q

Question: What does PCRE stand for?

A

Perl Compatible Regular Expressions

76
Q

Question: What prefix do functions in PHP that deal with PCRE start with?

A

preg

I.e. preg_match - reg ex

77
Q

Task: Determine whether a string matches a given regex pattern

A

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

78
Q

Task: Split a string at the point where a regex matches

A

array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

79
Q

Question: preg_split splits a string using a regex, is the pattern included in the output?

A

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
Q

Question: What is the difference between preg_match and preg_match_all?

A

preg_match_all will return (through the array) all of the matches, not just the first.

81
Q

Task: Encode an image appropriately for storing in a database

A

string base64_encode ( string $data )

82
Q

Task: Determine the name of a file given a path

A

string basename ( string $path [, string $suffix ] )

83
Q

Task: Determine the date / time of the last file modification?

A

int filemtime ( string $filename )

84
Q

Task: Reset an arrays internal pointer to the first element.

A

mixed reset ( array &$array )

NOTE: Reset will return the first element in the aray

85
Q

Task: Run a function over each element in an array in a recursive function

A

bool array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] )

86
Q

Task: Sort an array by key in reverse

A

bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

87
Q

Task: Sum an array containing numerical elements?

A

number array_sum ( array $array )

88
Q

Task: Test for a scalar variable?

A

bool is_scalar ( mixed $var )

89
Q

Task: Create an array with numbers between 4 and 16 that are divisible by 4 (in one function, no control statements)

A

array range ( mixed $start , mixed $end [, number $step = 1 ] )

range(4,16,4);

90
Q

Task: Take an array and randomise the elements within it.

A

bool shuffle ( array &$array )

91
Q

Task: Split a string either into characters or at a specific point in a string

A

array str_split ( string $string [, int $split_length = 1 ] )

92
Q

Task: Decompress a gzip’d file

A

string gzuncompress ( string $data [, int $length = 0 ] )