PHP4WP3 – Using Functions

What are functions?

  • Funcitons
    • Reusable snippets of code that can be called multiple times
  • Functions are like variables for lines of code.

function syntax

function hello_world() {
  return "Hello World";
}

echo '<p>'. hello_world() . '</p>';

Functions can

  • Return a variable.
  • Print something out.

Function printing example of the same code

<?php
 function hello_world() {
    echo "Hello World";
  }

?>

<p><?php hello_world(); ?></p>

using function (return value,, so that it can be used again and again)

function is_bigger() {
   return 10 >= 5;
}

$bigger = is_bigger();//value is true
if ( $bigger ) {
 echo "The function return true.";
} else {
 echo "The function return false";
}

Passing Arguments

We can pass the variables or arguments to the function.

function is_bigger($a, $b) {
  return $a >= $b;
}

$bigger = is_bigger(10,5);

use php.net to find the inbuilt php functions.

Using functions in WordPress

https://developer.wordpress.org/reference/functions

Start with Template Tags, and Data Sanitization/Escaping as the beginner.

Writing your own functions

Palindrome function.

<?php
  function is_palindrome( $string ) {
    $pal_check = ( $string == strrev($string) );
    return $pal_check;
  }
  var_dump( is_palindrome( "mom" ));//True
  var_dump( is_palindrome( "Mom" ));//False but should be true
  var_dump( is_palindrome( "Race Car" ));//False but should be true
?>

Modified palindrome

<?php
  function is_palindrome( $string ) {
    $string = strtolower( $string );
    $string = str_replace(' ','', $string);
    $pal_check = ( $string == strrev($string) );
    return $pal_check;
  }

  var_dump( is_palindrome( "Race Car" ));//True now
?>

Making the code shorter

<?php
  function is_palindrome( $string ) {
    $string = str_replace(' ','', strtolower( $string ));
    return $string == strrev($string);
  }

  var_dump( is_palindrome( "Race Car" ));
?>

Challenge: Write your own function to compare two numbers

Program created by me

<?php
  function compare_function ($a, $b) {
    if ($a > $b) {
      echo "$a is the bigger number";
    } else if ( $b > $a) {
      echo "$b is the bigger number";
    } else {
      echo "Both numbers are equal";
    }
  }

  compare_function( 10, 12);
  


?>

Shorter way to write it.

<?php
  function compare_function ($a, $b) {
    if ($a >= $b) {
      return $a;
    }
    return $b;
  }

  var_dump(compare_function( 10, 12));
  


?>
Subscribe
Notify of
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x