{"id":462,"date":"2018-08-10T00:47:02","date_gmt":"2018-08-10T00:47:02","guid":{"rendered":"https:\/\/www.go4expert.com\/tutorials\/?p=462"},"modified":"2018-08-14T00:54:06","modified_gmt":"2018-08-14T00:54:06","slug":"php-functions","status":"publish","type":"post","link":"https:\/\/www.go4expert.com\/tutorials\/php-functions\/","title":{"rendered":"PHP Functions"},"content":{"rendered":"<p>A function is a unit of a program or a block of code consisting of a set of statements. A function generally performs a specific task and it has a specific purpose in a program. Functions play an important role in programming because instead of writing repetitive and redundant code for frequently performed tasks we can just define a function and then we can call it whenever required.<\/p>\n<p>A function in a PHP page will never get executed when the PHP page loads. It will get executed only when the function is called.<\/p>\n<p>PHP offers more than a 1000 built-in functions. It also provides users with the facility to define their own functions because often users need to define their own custom functions.<\/p>\n<p>There are 2 essential aspects of working with functions. They are<\/p>\n<ol>\n<li>Creating a PHP function<\/li>\n<li>Calling a PHP function<\/li>\n<\/ol>\n<h2>Creating a PHP function<\/h2>\n<p>A PHP function should be created or defined before we attempt calling it. Some of the rules to be observed while defining a PHP function are as follows<\/p>\n<ol>\n<li>The keyword function is used along with the name of the function while defining the name of the function.<\/li>\n<li>The name of the function should be an intuitive name because it should indicate the purpose of the function. We can then ensure that the function is easily reusable.<\/li>\n<li>All the statements of the function are enclosed within curly braces {}.<\/li>\n<\/ol>\n<p>The basic syntax of creating a PHP function is shown below.<\/p>\n<pre><div class=\"bbCodeBlock\"><div class=\"type\">Code: <\/div><textarea readonly=\"readonly\">function functionname()\r\n{\r\n    function statements;\r\n}<\/textarea><\/div><\/pre>\n<p><b>Example: <\/b><\/p>\n<p>The example code shown below has a function printMessage defined in it. The printMessage function prints a simple message when it is called.<\/p>\n<pre><div class=\"bbCodeBlock\"><div class=\"type\">Code: <\/div><textarea readonly=\"readonly\">&lt;?php\r\n\/\/function definition\r\nfunction printMessage() {\r\n    echo \"PHP is fun because it is easy\";\r\n}\r\n\r\n\/\/ calling the above function\r\nprintMessage();\r\n\/*the output is \u201cPHP is fun because it is easy\u201d. The function printMessage is called, then the echo statement in the function gets executed*\/\r\n?&gt;<\/textarea><\/div>\r\n<\/pre>\n<h2>Functions with Parameters<\/h2>\n<p>Often we need to pass data to a function because the function may need to perform some operations on the data which is external to the function. Hence arguments are used. Arguments are the values that are passed to a function when we call it.<\/p>\n<p>Arguments can only be passed to a parameterized function i.e. a function which has been defined to accept arguments. The rules to define parameters for a function are as follows.<\/p>\n<ol>\n<li>Arguments are defined after the function name within parenthesis.<\/li>\n<li>More than one argument can be defined. All the arguments are separated using commas.<\/li>\n<li>Arguments behave like normal variables inside a function and can be used as such.<\/li>\n<\/ol>\n<p><b>Example: <\/b><br \/>\nThe following function takes two parameters , adds them and prints the sum<\/p>\n<pre><div class=\"bbCodeBlock\"><div class=\"type\">Code: <\/div><textarea readonly=\"readonly\">&lt;?php\r\nfunction sumFunction($n1, $n2) {\r\n    $sum = $n1 + $n2;\r\n    echo \"Sum of two numbers : $sum\";\r\n}\r\nsumFunction(50,40);\r\n\/\/ the output is \u201cSum of two numbers is 90\u201d because of the echo statement inside the function that is called\r\n?&gt;<\/textarea><\/div>\r\n<\/pre>\n<h2>Default Values for Function Parameters<\/h2>\n<p>Sometimes default values need to be set for the parameters of a function because the user may not pass any arguments while calling the function. Hence default values are assumed for the parameter values.<\/p>\n<p>The following function prints NULL if the function does not pass any value.<\/p>\n<pre><div class=\"bbCodeBlock\"><div class=\"type\">Code: <\/div><textarea readonly=\"readonly\">&lt;?php\r\nfunction printMe($param = NULL) {\r\n    print $param;\r\n}\r\n\r\nprintMe(\"I am a PHP program \");\r\n\/\/ the output will be \u201cI am a PHP program\u201d because it is passed as an argument to the function printMe\r\nprintMe();\r\n\/\/ the output will be \u201cNULL\u201d as no argument is passed and the default value is assumed\r\n?&gt;<\/textarea><\/div><\/pre>\n<h2>Returning values from a PHP function<\/h2>\n<p>Functions can return a value using the return statement. A function can execute some statements and then it can return a simple value or an object. When the return statement executes it stops the execution of the function and sends the value specified in the return statement back to the calling script. A return statement consists of the return keyword along with the value to be returned.<\/p>\n<p><b>Example: <\/b><\/p>\n<p>The following example shows a function that accepts two parameters. It adds them and then returns the sum to the calling program. Here the return keyword is used to return a value from the function.<\/p>\n<pre><div class=\"bbCodeBlock\"><div class=\"type\">Code: <\/div><textarea readonly=\"readonly\">&lt;?php\r\nfunction addnum($num1, $num2) {\r\n    $sum = $num1 + $num2;\r\n    return $sum;\r\n}\r\n$returnvalue = addnum(20, 30);\r\n\r\necho \"Value Returned from the function : $returnvalue\";\r\n?&gt;<\/textarea><\/div>\r\n<\/pre>\n<p><b>Output:<\/b><br \/>\nValue Returned from the function: 50<\/p>\n<h2>Passing Arguments by Reference<\/h2>\n<p>Passing an argument by reference is so called because we pass a reference to the variable as an argument. Hence the address of the variable is passed as a parameter while calling the function. Normally we pass arguments using the pass by value method where the copy of the variable value is passed to the function.<\/p>\n<p>Passing arguments by reference is sometimes necessary because we need to manipulate and change the actual variables rather than copies of variables.<\/p>\n<p>Hence any changes made to an argument which is passed by reference will change the value of the original variable.<\/p>\n<p>We can pass an argument by reference by adding a '&amp;' to the variable name in either the function definition or the function call. The function will then receive the address of the variable rather than a copy of the variable<\/p>\n<p><b>Example:<\/b><\/p>\n<p>The following example shows both pass by reference and pass by value<\/p>\n<pre><div class=\"bbCodeBlock\"><div class=\"type\">Code: <\/div><textarea readonly=\"readonly\">&lt;?php\r\n\/\/ the below function uses a pass by value method because of which $orignum will not change\r\nfunction addfour($num) {\r\n    $num += 4;\r\n}\r\n\/\/ the below function uses a pass by reference method because of the &amp; in the parameter\r\nfunction addseven(&amp;$num) {\r\n    $num += 7;\r\n}\r\n\r\n$orignum = 20;\r\naddfour( $orignum );\r\necho \"Original Value is.. $orignum\";\r\n\/\/ the output is \"Original Value is.. 24\" and the variable value changes because it was a pass by reference\r\n\r\naddSeven( $orignum );\r\necho \"Original Value is.. $orignum\";\r\n\/\/ the output is \"Original Value is.. 24\" and the variable value does not change because it was a pass by value\r\n?&gt;<\/textarea><\/div><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>A function is a block of code consisting of a set of statements which generally performs a specific task and has a specific purpose in a program.<\/p>\n","protected":false},"author":1,"featured_media":210,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[7],"tags":[],"class_list":{"0":"post-462","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-php","8":"entry"},"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>PHP Functions - Go4Expert Tutorials<\/title>\n<meta name=\"description\" content=\"A function is a block of code consisting of a set of statements which generally performs a specific task and has a specific purpose in a program.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.go4expert.com\/tutorials\/php-functions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PHP Functions - Go4Expert Tutorials\" \/>\n<meta property=\"og:description\" content=\"A function is a block of code consisting of a set of statements which generally performs a specific task and has a specific purpose in a program.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.go4expert.com\/tutorials\/php-functions\/\" \/>\n<meta property=\"og:site_name\" content=\"Go4Expert Tutorials\" \/>\n<meta property=\"article:published_time\" content=\"2018-08-10T00:47:02+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2018-08-14T00:54:06+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.go4expert.com\/tutorials\/wp-content\/uploads\/2018\/07\/PHP.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"770\" \/>\n\t<meta property=\"og:image:height\" content=\"385\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"shabbir\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"shabbir\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.go4expert.com\/tutorials\/php-functions\/\",\"url\":\"https:\/\/www.go4expert.com\/tutorials\/php-functions\/\",\"name\":\"PHP Functions - Go4Expert Tutorials\",\"isPartOf\":{\"@id\":\"https:\/\/www.go4expert.com\/tutorials\/#website\"},\"datePublished\":\"2018-08-10T00:47:02+00:00\",\"dateModified\":\"2018-08-14T00:54:06+00:00\",\"author\":{\"@id\":\"https:\/\/www.go4expert.com\/tutorials\/#\/schema\/person\/187ce4675295e6b09b98a9374ce2fec6\"},\"description\":\"A function is a block of code consisting of a set of statements which generally performs a specific task and has a specific purpose in a program.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.go4expert.com\/tutorials\/php-functions\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.go4expert.com\/tutorials\/php-functions\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.go4expert.com\/tutorials\/php-functions\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.go4expert.com\/tutorials\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PHP Functions\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.go4expert.com\/tutorials\/#website\",\"url\":\"https:\/\/www.go4expert.com\/tutorials\/\",\"name\":\"Go4Expert Tutorials\",\"description\":\"Programming And Web Development Tutorials\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.go4expert.com\/tutorials\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.go4expert.com\/tutorials\/#\/schema\/person\/187ce4675295e6b09b98a9374ce2fec6\",\"name\":\"shabbir\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.go4expert.com\/tutorials\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/303ce933c6bfabf6ac58bc870c696a1d5ef98012ecb820a4a7921853b813406f?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/303ce933c6bfabf6ac58bc870c696a1d5ef98012ecb820a4a7921853b813406f?s=96&d=mm&r=g\",\"caption\":\"shabbir\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"PHP Functions - Go4Expert Tutorials","description":"A function is a block of code consisting of a set of statements which generally performs a specific task and has a specific purpose in a program.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.go4expert.com\/tutorials\/php-functions\/","og_locale":"en_US","og_type":"article","og_title":"PHP Functions - Go4Expert Tutorials","og_description":"A function is a block of code consisting of a set of statements which generally performs a specific task and has a specific purpose in a program.","og_url":"https:\/\/www.go4expert.com\/tutorials\/php-functions\/","og_site_name":"Go4Expert Tutorials","article_published_time":"2018-08-10T00:47:02+00:00","article_modified_time":"2018-08-14T00:54:06+00:00","og_image":[{"width":770,"height":385,"url":"https:\/\/www.go4expert.com\/tutorials\/wp-content\/uploads\/2018\/07\/PHP.jpg","type":"image\/jpeg"}],"author":"shabbir","twitter_card":"summary_large_image","twitter_misc":{"Written by":"shabbir","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.go4expert.com\/tutorials\/php-functions\/","url":"https:\/\/www.go4expert.com\/tutorials\/php-functions\/","name":"PHP Functions - Go4Expert Tutorials","isPartOf":{"@id":"https:\/\/www.go4expert.com\/tutorials\/#website"},"datePublished":"2018-08-10T00:47:02+00:00","dateModified":"2018-08-14T00:54:06+00:00","author":{"@id":"https:\/\/www.go4expert.com\/tutorials\/#\/schema\/person\/187ce4675295e6b09b98a9374ce2fec6"},"description":"A function is a block of code consisting of a set of statements which generally performs a specific task and has a specific purpose in a program.","breadcrumb":{"@id":"https:\/\/www.go4expert.com\/tutorials\/php-functions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.go4expert.com\/tutorials\/php-functions\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.go4expert.com\/tutorials\/php-functions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.go4expert.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"PHP Functions"}]},{"@type":"WebSite","@id":"https:\/\/www.go4expert.com\/tutorials\/#website","url":"https:\/\/www.go4expert.com\/tutorials\/","name":"Go4Expert Tutorials","description":"Programming And Web Development Tutorials","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.go4expert.com\/tutorials\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.go4expert.com\/tutorials\/#\/schema\/person\/187ce4675295e6b09b98a9374ce2fec6","name":"shabbir","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.go4expert.com\/tutorials\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/303ce933c6bfabf6ac58bc870c696a1d5ef98012ecb820a4a7921853b813406f?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/303ce933c6bfabf6ac58bc870c696a1d5ef98012ecb820a4a7921853b813406f?s=96&d=mm&r=g","caption":"shabbir"}}]}},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/www.go4expert.com\/tutorials\/wp-content\/uploads\/2018\/07\/PHP.jpg","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p9JSSi-7s","_links":{"self":[{"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/posts\/462","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/comments?post=462"}],"version-history":[{"count":8,"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/posts\/462\/revisions"}],"predecessor-version":[{"id":484,"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/posts\/462\/revisions\/484"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/media\/210"}],"wp:attachment":[{"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/media?parent=462"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/categories?post=462"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.go4expert.com\/tutorials\/wp-json\/wp\/v2\/tags?post=462"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}