Learn PHP from Scratch Day -9

Learn PHP from Scratch Day -9
Learn PHP from Scratch Day -9

PHP Function: Numeric, Built in, String, Date, User Defined

What is a Function? & Why use Functions?

In coding life it's better to code once and re-use it multiple times. Suppose you have to add two number 2&4 then you would do it in PHP as 2+4 using arithmetic + operator. But what if the need of system is dynamic ? Means we don't know what are these two numbers to be added they might depends upon certain conditions or user inputs. Then in that case you can't just write some static operations in code. So here is the birth of / intro of functions and methods.!!

So wat we do in function we have some arguments , it's not compulsory you can have zero arguments to the function too. What are arguments ? As per w3school

Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

Then you just create one function which accepts two dynamic variables which are condition dependent or user inputs, and you simply add them. Cause you can also add variables in PHP. So even if input varies you will get the correct addition of two numbers.

Following are the some good reasons to use functions in PHP.

  • Better code organization— functions allow us to group blocks of related code that perform a specific task together.
  • Reusability — once defined, a function can be called by a number of scripts in our PHP files. This saves us time of reinventing the wheel when we want to perform some routine tasks such as connecting to the database
  • Easy maintenance- updates to the system only need to be made in one place.

Built in Functions

Not every function you going to write, PHP it self provides you mostly required functions , like date & time related functions, String operations like concatenation, string length calculation , arrays related functions and so on. PHP has over 700 functions built in that perform different tasks !!!!

These built-in functions further can be divided as follows

A]; String Functions

B]; Numeric Functions

C]; Date functions

D]; Files related Functions

E]; Database related Functions

As there 700+ built-in functions we are not giving all you at once. But in this doc will share some which are mostly used.

Some PHP Built in functions

Some PHP Built-in functions

String Functions

These are functions that manipulate string data, refer to the article on strings for implementation examples of string functions

Here are some mostly used String functions

PHP String Functions

PHP String Functions

Numeric Functions

Numeric functions are function that return numeric results.

PHP Numeric Functions

PHP Numeric Functions

Date Function

The date function is used to format Unix date and time to human readable format. Some of theme are below,

1.checkdate():This function will let us validate a Gregorian data.

2.date_add(): This function will let add days, months, years, hours, minutes and also seconds to the date.

3.date_create_from_format():The above date time function will return a Date Time Object formatted which is new according to the specific format.

4.date_create(): The date_create() function will return a new DateTime Object

5.date_date_set():The date_date_set() function will help you to set a new date in PHP programming language.

6.date_default_timezone_get(): The date_default_timezone_get() function will help in returning the default timezone which is used by all the time/date functions.

7.date_default_timezone_set(): The date_default_timezone_set() function will help you in setting the default time zone which can be used by all the Date Time functions.

8. date_diff(): The date_diff() function will return the difference between the two dates in PHP programming language.

9. date_format():The date_format() function will help in returning the date formatted according to the format which is specified in the PHP programming language.

10. date_get_last_errors():The date_get_last_errors() function helps in returning the errors/warnings which are found in the date string in PHP programming language.

11. date_interval_create_from_date_string():The date_interval_create_from_date_string() function will help in setting up the date interval which are from the string's relative parts in PHP programming language.

12. date_interval_format(): The date_interval_format() function will help in formatting the interval in the PHP programming language.

13. date_isodate_set():The date_isodate_set() function will help in setting the ISO date in PHP programming language.

14. date_modify():The date_modify() function will help you in modifying the timestamp in the PHP programming language.

15. date_offset_get(): The date_offset_get() function will help in returning the timezone's offset in the PHP programming language.

16. date_parse_from_format(): The date_parse_from_format() function will help in returning the associative array with some detailed info about a specific date according to the specified format in PHP programming language.

17. date_parse(): The date_parse() function will help you in returning the associative array with the detailed info regarding a specific/specified date in PHP programming language.

18. date_sub(): The date_sub() function will help in subtracting the days, the months, the years, the hours, the minutes and the seconds form date in PHP programming language.

19. date_sun_info(): The date_sun_info() function will help you in returning the array/arrays which contains the info regarding the sunrise/sunset and also the twilight begin/end which are for a specified day and also for a specified location in PHP programming language.

20. date_sunrise(): The date_sunrise() function will help you in returning the sunrise time for a specified location and the specified date in PHP programming language.

21. date_sunset(): The date_sunset() function will help in returning the sunset time for the specified location and the specified day/date in PHP programming language.

22. date_time_set(): The date_time_set() function will help you in setting the time in PHP programming language.

23. date_timestamp_get(): The date_timestamp_get() function will help in returning the Unix's timestamp in PHP programming language.

24. date_timestamp_set(): The date_timestamp_set() function will help us in setting the time and date based on the Unix's timestamp in PHP programming language.

25. date_timezone_get(): The date_timezone_get() function will help in returning the zone of the time which is given from the DateTime Object in PHP programming language.

26. date(): The date() function will help in formatting the local time and date in PHP programming language.

27. getdate(): The getdate() function will help in returning the time/date info/information of the timestamp or the current local time/date.

28. gettimeofday(): The gettimeofday() function will help in returning the current time.

29. gmdate(): The gmdate() function will help in returning the formatted a GMT/UTC time and date.

30. gmmktime(): The gmmktime() function will help for a GMT date by returning the UNIX time

31. gmstrftime(): The gmstrftime() function will help to format a UTC/GMT time and time according to the locale setting/settings.

32. idate(): The idate() function will format the local date/time just as the integer.

33. localtime(): The localtime() function will help us in returning the local system time.

34. microtime(): The microtime() function will help in returning the current Unix timestamp/timestamps with microseconds.

35. mktime(): The mktime() function will help by returning the Unix timestamp for the date.

36. strftime(): The strftime() function formats the local date and/or local time according to the local settings.

37. strptime(): The strptime() function will help in parsing the date/time which is generated strftime().

38. strtotime(): The strtotime() function will help in parsing an English textual datetime into the Unix timestamp.

39. time(): The time() function will help in returning the current time as a Unix timestamp.

40. timezone_abbreviations_list(): The timezone_abbreviations_list() function will help in returning the associative array which contains the DST, offset and also the timezone's name.

41. timezone_identifiers_list(): The timezone_identifiers_list() function will help in returning the indexed array with also all the time zone identifiers.

42. timezone_locaiton_get(): The timezone_location_get() function will helps in returning the location info/information for the specified time zone.

43. timezone_name_form_abbr(): The timezone_name_form_abbr() function will help in returning the timezone's name from its abbreviation.

44. timezone_name_get(): The timezone_name_get() function will help in returning the timezone's name.

45. timezone_offset_get(): The timezone_offset_get() function will help in returning the timezone's offset from the Greenwich Mean Time (GMT).

46. timezone_open(): The timezone_open() will help in creating the new DateTIme zone's object.

47. timezone_transitions_get(): The timezone_transitions_get() function will help in returning all the transactions for the timezone.

48. timezone_version_get(): The timezone_version_get() function will help us in returning the time zoned version.

Why use User Defined Functions?

Even we have too many built-in functions still those are not sufficient to make coder life easy. Coder has to make his life easy with the help of writing User defined functions, these functions come in handy when;

  • you have daily task in your application such as adding data to the database
  • performing validation checks on the input data
  • Authenticating users in the system etc.

These activities will be spread across a number of pages.

Creating a function that all these pages can be calling is one of the features that make PHP a powerful scripting language.

    • Function names must start with a letter or an underscore but not a number
    • The function name must be unique
    • The function name must not contain spaces
    • It is considered a good practice to use descriptive function names.
      • Functions can optionally accept parameters and return values too.

Let's now create our first function. We will create a very basic function that illustrates the major components of a function in PHP.

Output:

3

HERE,

      • "function…(){…}" is the function block that tells PHP that you are defining a custom function
      • "add_numbers" is the function name that will be called when using the function
      • "()" can be used to pass parameters to the function.
      • "echo ‘Hello function!';" is the function block of code that is executed. It could be any code other than the one used in the above example.

Let's now look at a fairly complex example that accepts a parameter and display a message just like the above function.

Suppose we want to write a function that prints the user name on the screen, we can write a custom function that accepts the user name and displays it on the screen.

The code below shows the implementation.

Output:

Hello Swapnil

HERE,

      • "…($name){…" is the function parameter called name and is initialized to nameless. If no parameter is passed to the function, nameless will be displayed as the name. This comes in handy if not supplying any parameter to the function can result in unexpected errors.

Let's now look at a function that accepts a parameter and then returns a value. We will create a function that converts kilograms to milligrams. The kilograms will be passed as a parameter. The function will return the milligrams equivalent to the passed kilograms. The code below shows the implementation.

Output:

100000

Summary

    • Functions are blocks of code that perform specific tasks
    • Built in functions are functions that are shipped with PHP
    • PHP has over 700 built in functions
    • String functions manipulate string data
    • Numeric functions manipulate numeric data
    • Date functions manipulate date data
    • User defined functions are functions that you can create yourself to enhance PHP