function in php

Sharing is caring!

PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.

You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.

There are two parts which should be clear to you −

  • Creating a PHP Function
  • Calling a PHP Function

In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.

Creating PHP Function

Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.

Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below −

<html>
   
   <head>
      <title>Writing PHP Function</title>
   </head>
   
   <body>
      
      <?php
         /* Defining a PHP Function */
         function writeMessage() {
            echo "You are really a nice person, Have a nice time!";
         }
         
         /* Calling a PHP Function */
         writeMessage();
      ?>
      
   </body>
</html>

This will display following result −

You are really a nice person, Have a nice time!

PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.

<html>
   
   <head>
      <title>Writing PHP Function with Parameters</title>
   </head>
   
   <body>
   
      <?php
         function addFunction($num1, $num2) {
            $sum = $num1 + $num2;
            echo "Sum of the two numbers is : $sum";
         }
         
         addFunction(10, 20);
      ?>
      
   </body>
</html>

This will display following result −

Sum of the two numbers is : 30

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable’s value.

Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.

Following example depicts both the cases.

<html>
   
   <head>
      <title>Passing Argument by Reference</title>
   </head>
   
   <body>
      
      <?php
         function addFive($num) {
            $num += 5;
         }
         
         function addSix(&$num) {
            $num += 6;
         }
         
         $orignum = 10;
         addFive( $orignum );
         
         echo "Original Value is $orignum<br />";
         
         addSix( $orignum );
         echo "Original Value is $orignum<br />";
      ?>
      
   </body>
</html>

This will display following result −

Original Value is 10
Original Value is 16 

PHP Functions returning value

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.

<html>
   
   <head>
      <title>Writing PHP Function which returns value</title>
   </head>
   
   <body>
   
      <?php
         function addFunction($num1, $num2) {
            $sum = $num1 + $num2;
            return $sum;
         }
         $return_value = addFunction(10, 20);
         
         echo "Returned value from the function : $return_value";
      ?>
      
   </body>
</html>

This will display following result −

Returned value from the function : 30

Setting Default Values for Function Parameters

You can set a parameter to have a default value if the function’s caller doesn’t pass it.

Following function prints NULL in case use does not pass any value to this function.

<html>
   
   <head>
      <title>Writing PHP Function which returns value</title>
   </head>
   
   <body>
      
      <?php
         function printMe($param = NULL) {
            print $param;
         }
         
         printMe("This is test");
         printMe();
      ?>
      
   </body>
</html>

This will produce following result −

This is test

Dynamic Function Calls

It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.

<html>
   
   <head>
      <title>Dynamic Function Calls</title>
   </head>
   
   <body>
      
      <?php
         function sayHello() {
            echo "Hello<br />";
         }
         
         $function_holder = "sayHello";
         $function_holder();
      ?>
      
   </body>
</html>

This will display following result −

Hello

php functions – practice makes perfect

If you are new to programming, then this lesson might or might not seem like overkill. If you are having a hard time understanding lessons, the best piece of advice would be to do your best the first time, then be sure to come back tomorrow and next week and see if it makes anymore sense. Chances are, after going through this tutorial more than once, with breaks in between, this topic will be mastered.

Comments 53

  • I aall tthe time emailed thnis webb sitte post page to all my contacts,
    forr thee reasson tat iif like to read itt thenn mmy contacts will too.
    I aam sure thiss parfagraph hass touchwd alll thhe internet
    users, its resally really pleasant piesce oof writing
    oon buildinhg up neww webpage. I wilkl rigt awway grwb your rss aas I can’t inn finding
    yokur email sibscription link or e-newsletter service.
    Do yyou haave any? Please llet mme recognise iin order tat I cohld subscribe.
    Thanks. http://foxnews.co.uk/

  • Her unusual otɦеr woгld endured and surfaced ᴡhen it wished, hoԝever it was nevеr with exciting oг compⅼetely
    hɑppy news.

  • I loved as much as you’ll receive carried out
    right here. The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get got an impatience over that you wish be delivering the
    following. unwell unquestionably come more formerly
    again as exactly the same nearly very often inside case you shield this increase.

  • I was wondering if you ever thought of changing the structure of your site?
    Its very well written; I love what youve got to say.

    But maybe you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having one or two images.
    Maybe you could space it out better?

  • I think this is among the most important information for me.
    And i’m glad reading your article. But should remark on some general things,
    The web site style is perfect, the articles is really nice :
    D. Good job, cheers

  • Auѕ ԁeг Perspektive des Urhebers ҝann ԁaѕ Streaming
    als ein Mittel ցesehen werden, seine Werke zս präsentieren undd trotzԁem technisch die Möglichkeit zս behalten, diе Verwertung zu kontrollieren սnd an Ԁer Nutzung sᥱiner Werke ᴢu verdienen. http://www.plazoo.com/

  • I know this website offers quality depending articles or reviews and extra material, is there any other web page which offers these data in quality?

  • Woah! I’m really enjoying the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between user
    friendliness and visual appearance. I must say that you’ve
    done a fantastic job with this. Also, the blog loads very quick
    for me on Internet explorer. Outstanding Blog!

  • Almost everything previously referred to, seems like your amazing persons learn an excellent information on %BT%.
    I`m just starting my own personal website inside of this chosen issue.
    Probably will I get a consultation and among a new qualified professionals?

  • A propósito, os negócios nunca se processam de acordo com
    a lógica ou com os cálculos. http://podzone-ro.com/forum/home.php?mod=space&uid=623376&do=profile&from=space

  • Hi there very coopl website!! Maan .. Exceellent ..
    Superb .. I will bookmark your site and take the feeds additionally…I’m glad to find so many useful info right here within the post, wee need work out extra techniques on thius regard, thank yoou for sharing.

  • I’ve been browsing online more tha 4 hours today, yet I never found any interesting article like yours.

    It’s pretty worth enough for me. In my opinion, if all webb owners
    and bloggers made good content as you did, tthe web will bee a lot more useful than ever before.|
    I couldn’t resist commenting. Very well written!|
    I will immediatgely ggrasp your rrss eed as I can’t to fihd
    your e-mail subscription link or newsletter service.
    Do you have any? Kindly let me recognize in order that I maay just subscribe.
    Thanks.|
    It’s perfect time tto make some plans for the future
    and it is ttime to be happy. I’ve read this post and if I could I wish to suggest you some interesting thinngs or tips.
    Perhaps you can write next articles referring to this article.
    I want tto read more things about it!|
    It is appropriate time to make some plans for the longer term and it is time to be happy.
    I’ve lrarn this publish and if I could I wish to suggest you few fascinating issues or suggestions.
    Perhaps you could write next articles regarding this article.
    I deseire to learn more things approximately it!|
    I’ve been browsing on-line greater than three hours as of late, but I by no means discovered any fascinating article
    like yours. It is pfetty price sufficient for me. In my opinion, if all site owners and bloggers made
    just right content as you probhably did, the web wiol probably
    be much more helpful thawn ever before.|
    Ahaa, its nice discussion concerning this paragraph here at this website, I ave read all that, soo at this time me also commenting here.|
    I am sure this piece of writing has touched all the internet people, itss reallly really pleasant
    post on building up new webpage.|
    Wow,this piece of writinjg is fastidious, my sister is analyzing these things, thus I aam going tto inform her.|
    Saved as a favorite, I really like your blog!|
    Way cool! Some extremely valud points! I appreciate you writing this write-up and also the rest of the site is very good.|
    Hi, I do think this iss an excellent web site.

    I stumbledupon it 😉 I may come back yet again since i have book-marked it.
    Money and freedom is the greatest way to change, mmay you be rich annd continue to help other people.|
    Woah! I’m really lovijg the template/theme of this site. It’s simple, yet
    effective. A lot of times it’s difficut to get that “perfect balance”
    between superb usability and visual appeal.
    I must say you’ve done a amazing job with this. Additionally,
    the blog loads ver fast for me on Internet explorer. Excellent Blog!|
    These are really impressive ideas in concerning blogging.
    Youu have touched some nice poiints here. Any way keep up wrinting.|
    Eveeryone loves what you guys aare up too. This type of
    cclever work and exposure! Keep up the fantastic woprks guys I’ve incorporated you guys to my own blogroll.|
    Hello! Someone in my Facebook group shared this website wit us so
    I came to check it out. I’m definitely loving the information. I’m book-marking and
    will bbe tweeting this to my followers! Great blog and gfeat design and
    style.|
    I enjoy what you guys are up too. This sort of clever work and reporting!
    Keep up the superdb works guys I’ve included you guyts to our blogroll.|
    Howdy would you mind sharing which blog platform you’re
    using? I’m going to start my own blog in the near future
    but I’m having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask iss because yokur design seems different then most blogs and I’m looking for something completely unique.
    P.S My apologies for being off-topic but I had to ask!|
    Hi there would you mind letting me know which hosting company
    you’re working with? I’ve loaded your blog in 3 different web browsers and I
    must say this blog loads a lot faster tgen most. Can you suggest a
    good web hosting provider at a reasonable price? Thanks a lot, I
    appreciate it!|
    I love it when individuals come together and share opinions.
    Great blog, stick with it!|
    Thak youu for the good writeup. It in fact wass a amusement account it.

    Lookk advanced to far added agreeable from you! However, how
    can we communicate?|
    Howdy just wanted to give you a quichk heads up. The words in your post seem tto be running off the screen in Chrome.
    I’m not sure if this is a format issue or something to doo with internet
    browser compatibility but I figured I’d post to let you know.
    The layout look great though! Hope you get the problem solved soon.
    Thanks|
    This iss a topic whch is close to myy heart… Many thanks!

    Exactly where are your contact details though?|
    It’s very straightforward to find outt any matter on web as compared to books,
    as I found this post aat this web site.|
    Dooes your blog have a contact page? I’m havung trouble locating it but, I’d
    lioke to shoot you an email. I’ve got some suggestions for
    your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it grow over time.|
    Hola! I’ve been reading your website for a long time noow and finally got the braver to
    goo ahead and give you a shout out from New Caney Tx! Just wanted to say keep up the greaat job!|
    Greetings frfom California! I’m bored at work so I decided
    to browse your site onn my iphone during luch break.
    I love the info you provide here and can’t wait to take
    a look when I get home. I’m shocked at how fast your blopg loaded on my
    mobile .. I’m nott even using WIFI, just 3G .. Anyhow, fantastic site!|
    Its like you read my thoughts! You seem to grasp a llot about this, such as you
    wrote the e book in it or something. I think that yoou could
    do wih somme percent to force thee message home a little bit,
    however instead of that, this is fantastic blog.
    An excellent read. I will certainly be back.|
    I visited multiple sites but the audio quality for audio songs preent at this web page is actually fabulous.|
    Hello, i readd your blog occasionally and i own a similar one and i was just curious iif you get a lot of
    spam responses? If so how do you protect against it, any plugin or anything you can advise?
    I get so mucch lately it’s driving me insane so any assistance is vey much appreciated.|
    Greetings! Very helpful advice within this post! It’s the little changes that make the biggest changes.
    Thanks a lot for sharing!|
    I really love your blog.. Pleasant coloors & theme.

    Did you build this site yourself? Please reply back as I’m
    attempting to create my own personal blog annd woujld love to know where you got this from
    or just what the theme is called. Kudos!|
    Hello there! This bpog post couldn’t be wrtten much better!
    Going tnrough this post reminds me of my previous roommate!

    He continually kept preaching about this. I am gling
    to send this post to him. Fairly certain he wilol have a good
    read. I apprecite you for sharing!|
    Incredible! This blpog loks just like my oldd one!
    It’s on a completely different subject but
    it has pretty much the same page layout and design. Excellent chiice of colors!|
    There is definately a lot to leaqrn about this topic. I like all the points you have made.|
    You made some really good points there. I looked on the net for more info about the
    issue and found most people will go apong with your views on this web site.|
    Hi there, I check your new stuff on a regular basis.
    Your story-telling style is awesome, keep doing what you’re doing!|
    I simply could not go away ylur ssite before suggesting that
    I actuall loved the standard informattion an individual supply on your visitors?
    Is going to be again iincessantly tto check out new posts|
    I need to tto thank you for this very good read!!
    I absolutely enjoyed every bbit of it. I have you saved
    as a favorite too check out neww things you post…|
    What’s up, just wanted to say, I liked this article.
    It was helpful. Keep on posting!|
    Hello, I enjoy reading through your articloe post.
    I like to write a little comment to supportt you.|
    I always spent my half an hour to read this blog’s articles every dday along with a cup
    of coffee.|
    I eevery time emailed this blog powt page to all my associates,
    as if like to read it afterward my links will too.|
    My programmer is trying to convince me too move
    to .net from PHP. I have always dsliked the idea because of
    the expenses. But he’s tryiong none tthe less.
    I’ve been using Movable-type onn numerous websites for
    about a year and am nwrvous about switching to another
    platform. I have heard great things about blogengine.net.
    Is there a way I can import all my wordpress content into it?

    Any help would be really appreciated!|
    Hi there! I could have sworn I’ve been to this sijte before but after
    going through many of the articles I realized it’s new to me.
    Anyways, I’m definitely pleased I discovered it
    and I’ll be bookmarking it and checking back frequently!|
    Wonderful article! Thatt iss the kind of info that should be shared across the internet.
    Disgrace on the seek engines for no longer positioning this post higher!
    Come on over and seek advice from my website . Thank you =)|
    Heyya i am for the firsst time here. I found this board and I
    find It really useful & it helped mme oout much.
    I hope to give something back and aid others like yyou helped me.|
    Hello, I think your website could possibly be having web browser compatibility problems.
    When I take a look at your website in Safari, it looks
    fine however, if opening in Internet Explorer, it’s ggot
    some overlapping issues. I merely wanted to provide you with a quick
    heads up! Besides that, great site!|
    Somebody necessarily assist to make significantly posts I mighht state.

    That is the first time I frequented your website page and to this
    point? I surprised with the analysis you mae too make this
    actual pput up extraordinary. Excellent task!|
    Heya i am for the first time here. I found this
    boaard and I to find It really helpful & it helped me out
    a lot. I am hoping to provide something
    again and help othefs such as you aided me.|
    Good day! I simply wish too give you a big thumbs up for your excxellent info you have ggot right here on this post.
    I am returning tto your website foor more soon.|
    I all the time used to reaad article in news papers but now as I am a user
    of net therefore from now I am using net for articles or reviews, thanks to web.|
    Your method of telling the whole thing in thjis paragraph iis truly fastidious, every one can simply know it,
    Thanks a lot.|
    Hi there, I discovered your site by the usee oof Google whilst looking for a related matter, your web site came up,
    it appears good. I’ve bookmarked it in my google bookmarks.

    Hi there, simply was alert to your blog thdu
    Google, and found that it is realy informative. I’m going to watch out for brussels.

    I will appreciate in the event you proceed this in future.
    Many folks will probably be benefited from your writing.
    Cheers!|
    I’mcurious to find out what blog platform you have been working
    with? I’m having some small security issues with my latest
    blog aand I would lioe to find something more secure. Do you
    have any recommendations?|
    I’m extremely impressed with your writing skills and also
    with the layout on your blog. Is this a paid theme or did you customize
    it yourself? Either way keep up the excellent quality writing, it is rare
    to see a nice blog like thiis one these days.|
    I am extremely inspired along with yohr wwriting abilities and also witfh the structure to your blog.
    Is this a paid subject or did you customize it your self?
    Anyway stay up the excellent high quality writing, it is uncommon to look a
    great weblog liuke this one nowadays..|
    Hello, Neat post. There is a problem together with your web site
    in internet explorer, would test this? IE still is thhe
    marketplace chief and a huge portion of folks will leave out your magnificent writing
    because oof this problem.|
    I’m not sure where you are getting your info, but grest topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for magnificent info I was looking for this info for my mission.|
    Hi, i think that i saaw you visited mmy site so i came to “return the favor”.I’m trying to find things to enhance my web site!I suppose its ok to
    use some of your \

  • Normaly I don’t learn article oon blogs, however I would like to say
    that this write-up very compelled me to take a look at
    and doo so! Your writing taste has beeen amazed me. Thanks, quife
    great post.

  • Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but instead of that, this is magnificent blog. A fantastic read. I’ll certainly be back.

  • Have you ever thought about creating an ebook or guest authoring on other websites?
    I have a blog centered on the same ideas you discuss and
    would really like to have you share some stories/information. I know my subscribers would appreciate your work.
    If you’re even remotely interested, feel free to send me an email.

  • This site is fantastic, i truly adore it.

  • Woah I enjoy your posts, bookmarked! My spouse and i loved your posts.

  • It’s difficult to get well-informed people on this topic however you sound like you know what you’re speaking about!
    Many thanks for this post. I totally agree with what you are saying.
    Keep us posted.

  • Many thanks for such an amazing blog. Where else could anyone
    have that kind of info written in such a perfect way? I have a presentation that i’m presently working
    on, and I happen to be looking for such information.Thanks for
    blogging and i love your articles.

  • I had been honored to get a call from a friend as he discovered
    the important guidelines shared on the site.
    Browsing your article is a real wonderful experience.
    Many thanks for thinking of readers like me, and I wish you the best.

  • Woh I like your blog posts, saved to my bookmarks!

  • Hello i am kavin, its my first time to commenting anywhere, when i read this post i thought i could also create comment due
    to this brilliant paragraph.

  • Nice post. I learn something totally new aand challenging on blogs I stumbleupon every day.
    It’s always useful too read through content
    from oter authors and practice something from their websites.

  • Great post, I’m most likely to spend more time researching this subject.

  • Awesome content, I’m going to invest more time researching this topic.

  • Seriously great articles are found on this website, thank you for your contribution.

  • I have been reading out a lot of your articles and i
    can claim pretty nice stuff. I will ensure to bookmark your blog.

  • Yours is an excellent example of informative writing. I think my students could learn a
    lot from your writing style and your articles. I may share this article with them.

  • Great beat ! I ish to apprentice att the same time as you amend your website,
    how could i subscribe for a blog web site?The
    account aided me a applicable deal. I have been tiny bit familiar of this your broadcast provided brilliant clear idea.

  • I haven’t checked in here for a little while simply because I was
    thinking it was getting dull, but the last few posts are really good quality thus I guess I’ll
    add you back to my day-to-day bloglist. You deserve it my friend.

  • Stuff your moist footwear with newspaper to assist the leather maintain its shape whereas
    the shoes dry.

  • He agreed and whereas we ran collectively I requested him if
    he was a marathoner as a result of he appeared to have a really economical stride suited for long distance
    operating.

  • This time round he is spreading the love just a little bit by
    stunning consumers at a Foot Locker in NYC and helping them supra skytop 3 out in selecting
    their gear for the summer time Harden himself even picks up a few pairs.

  • Often these well-liked sneakers come in numerous colors simply to mark such special occasions because the Olympics where
    they are typically offered in colors that comemorate totally different international locations that may
    be collaborating.

  • For this very cause, many of the main shoe manufacturers have a variety of sport sneakers specially constructed to withstand the complexities and strains
    of varied specific actions whereas offering efficiency
    and luxury for the wearer.

  • And it made adidas and its founder a family name on football pitches in all places.

  • Black coat boots which includes a wedge are likewise increasingly
    in style relating to city lifetime.

  • Adidas later developed spiked shoes that could possibly be worn for various working distances.

  • Shoes are clothing, not something that determines my gender or sexual
    orientation.

  • Auch am sogenannten Athleisure-Boom, also Sportfunktionskleidung,
    die man auch im Büro oder beim Ausgehen anziehen kann,
    will Nike mitverdienen.

  • Adidas will proceed so that you can develop into known as adhering to it’s president, Driving college Dassler,
    whom initiated the actual company staying the shoe-manufacturing system throughout 1948.

  • Major thankies for the article. Cool.

  • Nike have released a spread alongside facet the Quick Strike Packs in relation to the forth coming world cup
    hosted in the South Africa 2010.

  • These nike shox shoes puts consolation into play with
    tremendous cushioning and a dynamic fit.

  • That high-topped design created by Nike Dunks is by now preferred in basketball shoes design.

  • Before the trip, White House aides had been coy about why Obama selected such a controversial backdrop for his speech.

  • Today, there are some shops that provide custom-made Air Force One footwear to observe the buyersandrsquo; choice of colour.

  • From this passage, we know that Marathon 10, the perfect trainers in Adidas Marathon family were launched into the market,
    which could accompany marathon runners in their runway to make success.

  • The calls for from the sports activities fraternity is being catered to with gusto and the launch of the Adidas Gazelle within the yr 1968 made historical past and the chapters proceed to
    run on. The shoe has simple styling, a flat sole and is made of
    soft leather-based.

  • Instead, they will find sneakers of their sizes posted by many alternative people
    with quite a lot of shoe needs and preferences.

  • The tennis footwear have a wide price vary which
    permits all to buy at the very least one pair of
    it. The better the quality the upper is the value.

  • The Colchester Rubber Company, the Goodrich and Spalding Co.
    together with some others have been the leading manufactures of the tennis sneakers.