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 15

  • 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?

  • Dores no geolho: tive sim, por uns dias caro regaço rodou p anexo, contudo
    pq cuba ilharga luxado no entanto a ajuntamento da articulado negativo no entanto no bairrista no lugar em
    que todo mundo tem. http://allycitizens.com/members/pedroeduardopo/activity/83329/

  • You have got one of the best online sites. http://bit.ly/2p7LTKb

  • Dageǥen gibt es ein Mittel: Abwarten, bis der gesamte
    Movie gestreamt istt ᥙnd erst dann anschauen. http://sizlar.com/UserProfile/tabid/427/userId/57382/Default.aspx

  • 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/

  • This site was… how do I say it? Relevant!! Finally
    I’ve found something that helped me. Thank you! http://srlaw.asia/index.php/component/k2/itemlist/user/11044

  • 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!

  • This website is a closing plus it clarifies a lot of stuff.
    Fantastic to find out, many thanks. http://bit.ly/2oYQd1x

  • Poker and rummy operators, along with thousands and thousands of players in India, are anxiously awaiting a rustic’s Supreme Court ruling that would determine the legality of
    both video games. Cyber due diligence for Paypal and on-line payment transferors in India must also be ensured.
    Attempt your hand at free poker, and as you get better
    and higher, we shall reward you by giving you real money
    in trade of your Free roll chips! It has been estimated
    that as many as 500,000 people in India play online poker for actual cash.
    In October 2013, The Indian Poker Affiliation, in petitions filed before the Karnataka Excessive Courtroom, complained that the police were
    harassing poker players by filing instances against them and raiding
    poker clubs. Perhaps this is because horse racing wouldn’t really have the
    identical enchantment have been there to be no betting
    concerned, however this is nonetheless a terrific instance of the contradictory playing
    laws in India.

    Having always been at the forefront of mind video games in the world,
    India is just not removed from World Poker domination, nevertheless, provides Ankit.

    Absolutely- taking part in on-line for free is without doubt one of the best methods to positive tune your abilities and get ready for some actual
    money action. Most of our listing of poker rooms offering games to
    India gamers gives you a good selection of game sorts. To place it simply, the final legal guidelines of India concerning playing apply until a
    state particularly sanctions it. So most have
    sanctioned lotteries, which would otherwise actually qualify as a recreation of chance,
    however they will still be permitted if the legislation supplies
    for it. Indians used to withdraw utilizing Netellers debit playing cards
    or Entropay’s plastic card, however this has been disabled
    for India.

    Inexpensive Internet Web site Designers India famous
    for Corporate Web site design and e-media providers.
    The 12 teams will be chosen through 70+ testing/qualifying
    bouts held across various cities in India over virtually three months, in addition to by means of online tournaments.
    They received plenty of selection in Poker be it Texas Maintain’em,
    Omaha Hi-Lo, 7 Card Stud all are prepared that will
    help you win some bucks. Earlier than we start our evaluate
    of the legal background to actual money poker inside India, I
    am going to simply make a point out of some useful poker pages here on winmoney101.
    Take for instance, Ravi Kinjal, who plays on , India’s largest On-line
    Poker Web site. You possibly can try your hand at Texas Hold’em
    Poker, Pot Restrict Omaha Poker, Single Table Match Poker, Free
    Poker, Free roll Poker Tournaments, Sit N
    Go Poker, Ring Poker, Multi Desk Poker Tournaments, and far more!

    Every online poker site has their very own strengths and weaknesses that you’ll want to
    evaluate with a purpose to reach a conclusion about whether
    you should play on the online poker site. The only test laid down by the Indian judiciary
    is that ability should dominate likelihood for a sport to be described as involving talent.
    The Machine however played his common model of
    tight solid poker but wasn’t capable of convert it right into a final desk money finish.
    The view of poker as a sport of ability has been gaining momentum in India lately, with a number of states having made strikes to loosen legal guidelines pertaining to it.
    These 108 players for 12 teams would be selected via 70+ rounds which would occur over a
    period of 3 months starting February subsequent yr.

    Our Flash sport builders have produced countless customized
    internet games and powerful online poker software.
    Mind youngster of FMCG major Dabur’s vice chairman Amit Burman, the
    primary season of the Poker Sports League ( PSL ) is likely to kick
    off early next 12 months. KHELO365 On-line Poker is the first on-line poker operator to be regulated by
    the Nagaland Talent Gaming License. Opening a
    Real Money account with us takes simply moments – merely hit Play for Actual Cash,
    fill out the web form and make your initial deposit to obtain your 200% Welcome Bonus.
    Amongst different things, visitors will find a day
    by day dose of articles with the newest poker information,
    dwell reporting from tournaments, unique videos, podcasts and a lot more.

    It’s expected that Pokernation and Zee Group will take steps to ensure that poker is
    totally recognised as a sport of skill by governments and the judiciary
    and doubts about taking part in poker for stakes are eradicated.
    Ensuing from ambiguity in legal tips, only West Bengal, Nagaland and Karnataka has categorised Poker as a legitimate,
    capability-based mostly sport, whereas in Goa, the game will likely be played solely in casinos.
    I see wealthy enterprise people undergo 1 or 2 Lakh of Rupee
    very quickly and never care so there’s loads of easy money.
    You possibly can select to play utilizing downloaded or flash versions of our software program, and might opt
    for both actual money recreation for real cash payouts or On the spot Play games utilizing digital chips.

    However, there’s different legislation in India which contradicts this to some extent.
    The craze caught up in India a number of years later, as non-resident Indians
    and students coming back from America started internet
    hosting poker video games at houses. As these web pages have their places of labor in overseas nations identical
    to the UK, they aren’t ruled by Indian legal tips
    regarding online playing. Consequently, it’s extremely troublesome to find out exactly what’s licensed
    and what’s not in India. The Golden Aces Poker
    League (GAPL) was organized by Golden Aces primarily based out of Bangalore which
    also operates the Golden Aces Cards Room in Bangalore.
    The location presently provides 4 poker variants – No
    Restrict Texas Hold’em, Pot Limit Omaha, Omaha Hello/Lo and Crazy
    Pineapple at various stakes.

    Day 4 being the final tournament of the weekend has a lower turnout of 68 gamers who participated within the 12k Headhunters tournament on Sunday
    night. Primarily it introduces a regulated strategy to
    licensing of online operators providing several types of video games – pinpointing them as talent-primarily
    based reasonably than gambling-based irrespective of how money is actually gained.
    To really say that India is a booming poker nation, on line casino poker must grow to
    be bigger. Mohan has fairly the participant resume with a number of wins within and outside India including a win on the inaugural Asian Poker Tour, Asian series’ Foremost Event in Goa back in 2012.
    The site is particularly tailor-made for Indian poker enthusiasts the place gamers can play on Freeroll as well as Actual Money Tables.

    Since 2004, we have been bringing you extremely scalable options
    for On-line Poker Software from India, with support for well-liked Desktop and Cell platforms.
    This a hundred and fifty chips poker set contains of six rolls of
    twenty-five chips which are valued at 5, 25, a hundred and 500.
    I simply want they’d offered a more strong packaging to carry all the chips in place once faraway from
    the unique packaging. Online Poker, Texas Holdem or one other are difficult but not troublesome believes Poker Nation. Thus, not solely the online poker web
    sites must be legally running in India but they have to even be in strict compliance with Indian revenue tax
    legal guidelines. In keeping with Kolkata-primarily based professional poker player Aditya
    Agarwal, who started enjoying over a decade in the past while
    studying in the US, India has only about 1,000 professional poker players, ninety
    five% of them male.

    Once acclimatized with free poker, player scan change to actual money online
    poker. The Supreme Court docket of India has to resolve these difficult points within the current litigation. The
    tiny state of Nagaland in North East India just lately change into the primary
    gambling jurisdiction in India to award a license to a web-based poker operator.
    Statisticians, economists and chess grandmasters globally
    have accepted that the sport of poker entails substantial diploma of skill.
    On this variation, the thought is to create the
    most effective 5-card poker hand from the seven playing
    cards available. Presently, he performs the India
    Poker Championship held on the Deltin Royale, and the Spartan Poker and Poker High tournaments on-line, from residence, for four to 6 hours a day.

    Poker in India is still in its infancy, however once the individual states begin to make it regulated
    there may be each probability that interest will explode.
    Rummy has already been pronounced to be a Recreation of Talent” by Indian Supreme Courtroom on quite a few counts and there may be nothing new about this Settled Legal Place” inside the present litigation. To add
    more to this on-line poker taking part in excitement we’ve got online
    poker tournaments that are listed on the primary web page with required particulars.

    It can take you a couple of minutes to register with us and you can start taking part in poker recreation on-line without any interference.

    Thus, not solely the web poker web sites must be legally working in India but they must even be in strict compliance with Indian income tax laws.

    PokerStars first ever sponsorship cope with Indian poker participant proved that poker is growing trade
    in the second most populated country on the
    earth. Collusion mainly represents purposeful fallacious play, the place
    a person performs the game in firm of two or extra players to take out
    or weaken other players on the desk. Subsequently gamers are
    battling to outlive the money bubble and subsequently the seat bubble, hence the
    match’s title. The Indian playing market is estimated to be price US$60 billion per year, of which about half is illegally guess.

    They have to decide on websites that host regulated actual cash online poker games,
    (ie) the sites that are licensed by a authorities authority positioned inside a particular geographic area(states of New Jersey, Nevada, and Delaware).

    Since gambling is determined primarily at
    the state degree though, this will not be as decisive as some assume it will, as all this is able to do is strike
    down a federal legislation applying to poker, however states nonetheless may
    provide you with their very own laws, as they do anyway.
    Over 50,000 individuals play online with these homegrown” online poker startups and ninety five p.c of India’s professional gamers are male.
    Ranging from the app variations of Fb to
    the standalone app, Poker turned an internet sensation. Signup and get and instant bonus of
    Rs.25 which you can use to play and hone your poker abilities.
    The fact that this law is still in effect after nearly 150 years tells us that this isn’t probably the most progressive nation in terms of gambling, and that’s actually
    true.

    To be on a safer facet, it’s higher to regulate to numerous techno authorized laws of India whereas opening an online based gambling, gaming and betting platform moderately than facing the
    punitive provisions of Indian laws. True to the immutable
    principle of the regulation of demand and supply, varied on-line
    poker websites have emerged and have been clamouring to lure the shoppers with exciting offers and promotions.
    Studies by economists and statisticians indicate that enjoying poker skilfully
    requires diverse information like sport theory, chance,
    statistics and danger administration. With a inhabitants of over a billion people, it could solely be
    a superb thing for gamers to have loads
    of choice in which poker site to play at.

    United Kingdom Gambling Commission (UKGC), world’s
    strongest federal physique to manage laws pertinent to on-line gaming,
    regulates real cash on-line poker games. Largely I’ve performed
    stay cash video games (residence games) in Hyderabad on weekends every time I could find
    time for poker; off late I’m playing extra on-line tourneys.
    Players ought to really feel secure in understanding that native or national authorities don’t seek to persecute or prosecute them.
    There is an exemption for games of skill, but the Indian government continues to
    be deciding whether or not online poker games fall into that class.

    So start enjoying the game of expertise, begin enjoying poker to have
    best user expertise and that too with our cash.
    I am presently working on an online poker faculty the place I
    intend to show the basics of poker strategy in a structured
    and organised method.

Leave a Reply

Your email address will not be published. Required fields are marked *