PHP Functions: User-Defined and System

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What is the primary benefit of using PHP functions in your code?

  • They automatically execute when a page loads, improving initial loading time.
  • They are only used for complex mathematical operations and provide optimized performance.
  • They allow for reusable blocks of code, reducing redundancy and making code cleaner. (correct)
  • They provide a way to directly interact with the server hardware for enhanced performance.

Which of the following is a valid example of calling a user-defined function named calculateSum with two arguments, $a and $b?

  • calculateSum;
  • function calculateSum($a, $b);
  • calculateSum($a, $b); (correct)
  • return calculateSum($a, $b);

If a PHP function is defined to accept two arguments but is called with only one, what is the likely outcome?

  • The function will execute normally but might produce unexpected results due to the missing argument.
  • The function will automatically assign a default value to the missing argument.
  • The missing argument will be treated as `NULL` within the function.
  • PHP will throw a warning or error, indicating that the expected number of arguments was not provided. (correct)

Which of the following is true regarding PHP's type declarations for function return values in PHP 7 and later?

<p>Enabling the <code>strict_types</code> requirement ensures that a 'Fatal Error' is thrown if the return value does not match the declared type. (D)</p>
Signup and view all the answers

In PHP, what is the purpose of string functions?

<p>To manipulate and format text within web applications. (B)</p>
Signup and view all the answers

What does the strlen() function in PHP return?

<p>The length of the string. (C)</p>
Signup and view all the answers

Which PHP function converts a string to lowercase?

<p><code>strtolower()</code> (C)</p>
Signup and view all the answers

What is the result of applying the ucwords() function to the string 'hello world'?

<p><code>Hello World</code> (B)</p>
Signup and view all the answers

Which function is used to find the position of the first occurrence of a substring within a string in PHP?

<p><code>strpos()</code> (A)</p>
Signup and view all the answers

What does the PHP function str_replace() do?

<p>It replaces all occurrences of a search string with a replacement string. (C)</p>
Signup and view all the answers

Which PHP function is used to extract a part of a string?

<p><code>substr()</code> (A)</p>
Signup and view all the answers

Which of the following functions removes whitespace from both the beginning and end of a string?

<p><code>trim()</code> (A)</p>
Signup and view all the answers

What is the primary purpose of the ltrim() function in PHP?

<p>To remove whitespace from the beginning of a string. (C)</p>
Signup and view all the answers

What does the rtrim() function in PHP do?

<p>Removes whitespace from the end of a string. (B)</p>
Signup and view all the answers

In PHP, what does the date() function primarily return?

<p>The current date and time, formatted as a string. (A)</p>
Signup and view all the answers

What value does the time() function return in PHP?

<p>The number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). (C)</p>
Signup and view all the answers

What is the primary purpose of the date_diff() function in PHP?

<p>To calculate the difference between two dates. (A)</p>
Signup and view all the answers

What is the purpose of the date_add() function in PHP?

<p>It adds an interval to a date. (A)</p>
Signup and view all the answers

If $date is a DateTime object in PHP, which function would you use to subtract 5 days from it?

<p><code>date_sub($date, date_interval_create_from_date_string('5 days'))</code> (D)</p>
Signup and view all the answers

You need to format a date in PHP to display only the year in four-digit format. Which format character should you use with the date() function?

<p><code>Y</code> (B)</p>
Signup and view all the answers

What is the correct date format code to get the full textual representation of a month, like 'January'?

<p><code>F</code> (B)</p>
Signup and view all the answers

You have a DateTime object $date. How would you format the time to display hours in 12-hour format with leading zeros and minutes with leading zeros?

<p><code>date_format($date, 'h:i')</code> (B)</p>
Signup and view all the answers

If you want to display the timezone abbreviation (e.g., EST, MDT) using the date() function, which format character should you use?

<p><code>T</code> (D)</p>
Signup and view all the answers

Which format character in the date() function represents the difference to Greenwich Mean Time (GMT) in hours (e.g., +0200)?

<p><code>O</code> (B)</p>
Signup and view all the answers

Which of the following represents the correct format to output the number of seconds since the Unix Epoch?

<p><code>date('U')</code> (A)</p>
Signup and view all the answers

Flashcards

PHP Functions

Reusable blocks of code that perform specific tasks making code cleaner and more efficient.

User Defined Function

A function that is created/defined by the user.

System Function

Functions built into PHP that are readily available for use, also known as built-in functions.

Function Arguments

Values passed into a function when it is called, acting as variables within the function.

Signup and view all the flashcards

Return Type Argument

Specifying the data type that a function will return after its execution.

Signup and view all the flashcards

PHP String Functions

Built-in tools in PHP that allow manipulation and working with text.

Signup and view all the flashcards

strlen()

Returns the length of a string.

Signup and view all the flashcards

strtolower()

Converts a string to lowercase.

Signup and view all the flashcards

strtoupper()

Converts a string to uppercase.

Signup and view all the flashcards

ucwords()

Capitalizes the first letter of each word in a string.

Signup and view all the flashcards

strpos()

Finds the position of the first occurrence of a substring in a string.

Signup and view all the flashcards

str_replace()

Replaces all occurrences of a search string with a replacement string.

Signup and view all the flashcards

substr()

Returns a part of a string.

Signup and view all the flashcards

trim()

Removes whitespace (or other characters) from both ends of a string.

Signup and view all the flashcards

ltrim()

Removes whitespace (or other characters) from the beginning of a string.

Signup and view all the flashcards

rtrim()

Removes whitespace (or other characters) from the end of a string.

Signup and view all the flashcards

date()

Returns the current date and time.

Signup and view all the flashcards

time()

Returns the Unix timestamp, representing the number of seconds since the Unix Epoch.

Signup and view all the flashcards

date_diff()

Calculates the difference between two dates.

Signup and view all the flashcards

date_add()

Adds an interval to a date.

Signup and view all the flashcards

date_sub()

Subtracts an interval from a date.

Signup and view all the flashcards

Study Notes

  • PHP functions are reusable code blocks that perform specific tasks.
  • Utilizing functions helps reduce redundancy, creating cleaner and more efficient code.

Types of Functions

  • User Defined Functions are custom functions created by the user.
  • System Functions are built-in functions that are part of the PHP language.

User Defined Functions

  • In addition to the built-in PHP functions, you can create your own functions.
  • Functions consist of a block of statements for repeated use in a program.
  • Functions do not automatically execute upon page load; they are executed through a function call.
  • The syntax for declaring a user-defined function starts with the word "function", followed by the function name, parentheses, and curly braces enclosing the code to be executed.
    • function functionName() { code to be executed; }

Function Arguments

  • Information can be passed to functions through arguments, which are like variables.
  • Arguments are specified inside the parentheses after the function name, separated by commas.

Return Type Argument

  • PHP 7 supports type declarations for the return statement.
  • Enabling strict requirements with type declarations throws a "Fatal Error" on a type mismatch, similar to function arguments.
  • To declare a type for the function return, add a colon (:) and the type before the opening curly bracket when declaring the function.

String Functions

  • PHP string functions are built-in tools designed to manipulate text within PHP.
  • They help with tasks such as finding string length, replacing parts, and converting text case.
  • These functions simplify text handling and formatting in web applications.

Basic String Functions

  • strlen(): Returns the length of a string.
  • strtolower(): Converts a string to lowercase.
  • strtoupper(): Converts a string to uppercase.
  • ucwords(): Capitalizes the first letter of each word in a string.

Searching and Replacing Functions

  • strpos(): Finds the position of the first occurrence of a substring in a string.
  • str_replace(): Replaces all occurrences of a search string with a replacement string.
  • substr(): Returns a part of a string.

Trimming Functions

  • trim(): Removes whitespaces (or other characters) from both ends of a string.
  • ltrim(): Removes whitespaces (or other characters) from the beginning of a string.
  • rtrim(): Removes whitespaces (or other characters) from the end of a string.

Date and Time Codes

  • Y: Represents a four-digit year.
  • y: Represents a two-digit year.
  • a: Lowercase AM or PM.
  • A: Uppercase AM or PM.
  • B: Swatch Internet time (000 to 999).
  • g: 12-hour format of an hour (1 to 12).
  • G: 24-hour format of an hour (0 to 23).
  • h: 12-hour format of an hour (01 to 12).
  • H: 24-hour format of an hour (00 to 23).
  • i: Minutes with leading zeros (00 to 59).
  • s: Seconds with leading zeros (00 to 59).
  • u: Microseconds (added in PHP 5.2.2).
  • e: The timezone identifier (e.g., UTC, GMT, Atlantic/Azores).
  • I (capital i): Indicates if the date is in Daylight Savings Time (1 if yes, 0 if no).
  • O: Difference to Greenwich Time (GMT) in hours (e.g., +0100).
  • P: Difference to Greenwich Time (GMT) in hours:minutes (added in PHP 5.1.3).
  • T: Timezone abbreviations (e.g., EST, MDT).
  • Z: Timezone offset in seconds; negative for timezones west of UTC (-43200 to 50400).
  • c: The ISO-8601 date format (e.g., 2013-05-05T16:34:42+00:00).
  • r: The RFC 2822 formatted date (e.g., Fri, 12 Apr 2013 12:01:05 +0200).
  • U: Seconds since the Unix Epoch (January 1, 1970 00:00:00 GMT).

Basic Date Functions

  • date(): Returns the current date and time.
  • time(): Returns the Unix timestamp.

Date Difference

  • date_diff(): Calculates the difference between two dates.
    • Example:
      • $date1 = date_create("2023-01-01");
      • $date2 = date_create("2024-01-01");
      • $diff = date_diff($date1, $date2);
      • echo $diff->format("%R%a days"); // Output: +365 days

Adding and Subtracting Dates

  • date_add(): Adds an interval to a date.
  • date_sub(): Subtracts an interval from a date.
    • Example:
      • $date = date_create("2023-01-01");
      • date_add($date, date_interval_create_from_date_string("10 days"));
      • echo date_format($date, "Y-m-d"); // Output: 2023-01-11

Midterm Lab Activity 1

  • Problem 1: Write a function factorial that takes a positive integer n and returns its factorial, which is the product of all positive integers less than or equal to n.
    • Example: echo factorial(5); // Output: 120
  • Problem 2: Write a PHP script that takes a date in the format Y-m-d and calculates the number of days until the next occurrence of that date.
    • Example: echo daysUntilNextOccurrence('2024-10-11'); // Output: (number of days until next occurrence)
  • Problem 3: Write a function reverseString that takes a string and returns the string reversed.
    • Example: echo reverseString("Hello, World!"); // Output: !dlroW ,olleH

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

PHP Functions Quiz
6 questions

PHP Functions Quiz

TrustingPeridot avatar
TrustingPeridot
PHP Functions
15 questions

PHP Functions

FavoriteNovaculite2263 avatar
FavoriteNovaculite2263
Use Quizgecko on...
Browser
Browser