Patrick Taylor

PHP examples

Code snippets

strings | arrays | loops | patterns | files | superglobals | functions | objects | other

Strings

Access individual characters in a string:
$string = "characters";
echo $string[2]; // a
Check for a string (2) in another string (1):
if (strstr($string1, $string2)) {
  // do something...
}
Locate the position of a substring in a string:
// Example 1
$string = 'characters';
$find = 'act';
$pos = strpos($string, $find);
if ($pos === FALSE) { // Note triple equals
  echo "$find was not found in $string";
} else {
  echo "$find was found in $string at position $pos";
}
// Example 2
$string = "abcdef abcdef";
$pos = strpos($string, "a", 1); // $pos = 7, not 0
// Example 3
$string = "pippa999female";
if (strpos($string, "pippa") === 0) {
  echo "Hello Pippa";
}
Check the length of a string:
if (strlen($string) == 0) { // If there isn't a string
  // do something...
}
Trim whitespace at each end of a string:
$string = trim($string);
Get a specified portion of a string:
$string = "the cat sat on the mat";
// Get 3 characters from character 5
echo substr($string, 5, 3);  // cat
// Get the last 3 characters
echo substr($string, -3);  // mat
// Get the last 3 characters but 4
echo substr($string, -7, 3);  // the
Repeat a string a specified number of times:
$string = "ha";
// Note: str_repeat includes the original instance
echo str_repeat($string, 6); // hahahahahaha
Strip HTML tags from a string:
$cleanText = strip_tags($text);
// To allow specified tags:
$allowedTags = 'write the (opening) tags';
$cleanText = strip_tags($text, $allowedTags);
Convert case:
$string = "aLExAnDeR tHE grEAt";
// First make all lowercase, then make first letters cap
$string = ucwords(strtolower($string));
echo $string; // Alexander The Great
// There is also strtoupper()
Count the number of words in a string:
$number = str_word_count($string);
Replace one instance of part of a string with something else:
$string = "pippa999female";
// Starting position = 5, length of instance = 3
$string = substr_replace($string, "1000", 5, 3);
echo "You are $string."; // You are pippa1000female.
Replace all instances of part of a string:
$inThis = str_replace("Replace this", "With this", $inThis);

[ back to top ]

Arrays

Create and access an enumerated array:
$myArray = array('John', 'Paul', 'George', 'Ringo');
echo $myArray[0]; // John
echo $myArray[3]; // Ringo
// Loop through the array to print all
foreach ($myArray as $val) {
  echo "$val "; // John Paul George Ringo
}
Create and access an associative array:
$myArray = array(
  "rhythm" => "John",
  "bass" => "Paul",
  "lead" => "George",
  "drums" => "Ringo"
)
echo $myArray["bass"]; // Paul
// Loop through the array to print all
foreach ($myArray as $key=>$val) {
  echo "$key: $val "; // rhythm: John bass: Paul etc
}
Split a string into an array using a separator:
// Example 1
$string = "the cat sat on the mat";
$myArray = explode(" ", $string); // Separator = " "
echo $myArray[0]; // the
echo $myArray[2]; // sat
// Example 2
$string = "less|is|more";
list($one, $two, $three) = explode("|", $string);
echo $one; // less
echo $three; // more
// Note that 'list' assigns a list of variables, eg:
$myArray = array('less', 'is', 'more');
// Get some
list($one, , $three) = $myArray;
echo "$three is not $one"; // more is not less
Make a string from an array, with glue in between:
$myArray = array("John", "Paul", "George", "Ringo");
// Glue = comma + space
echo implode(", ", $myArray); // John, Paul, George, Ringo
Extract only a specified part of an array:
$myArray = array("John", "Paul", "George", "Ringo");
// Example 1: start at element 3
$slice = array_slice($myArray, 2);
foreach ($slice as $val) {
  echo "$val "; // George Ringo
}
// Example 2: start two from the end and return one
$slice = array_slice($myArray, -2, 1);
foreach ($slice as $val) {
  echo "$val "; // George
}
// Example 3: start at the beginning and return two
$slice = array_slice($myArray, 0, 2);
foreach ($slice as $val) {
  echo "$val "; // John Paul
}
Replace one array with another:
// Source string
$string = "The name of the drummer was Ringo";
// Array containing search strings
$findArray = array("name", "drummer", "Ringo");
// Array containing replacement strings
$replaceArray = array("nationality", "manager", "British");
// Replace strings
echo str_replace($findArray, $replaceArray, $string);
// The nationality of the manager was British
Multiple search and replace:
// Create an array of source strings
$myArray = array("less is more", "John Paul George Ringo");
// Create arrays of search and replace strings
$search = array("less", "more", "Ringo");
$replace = array("enough", "not enough", "Pete");
// Replace and display
$myArray = str_replace($search, $replace, $myArray);
foreach ($myArray as $string) {
  echo "$string, "; // enough is not enough, John Paul George Pete 
}
Search a string for any of the values in an array:
foreach ($array as $val) {
  if (stripos($string, trim($val)) !== false) {
    echo "$val, "; // The array values found in string
  }
}
Make array strings into variables:
// Array of strings
$group = array('John', 'Paul', 'George', 'Ringo');
// List (make) all the variables
list($one, $two, $three, $four) = $group;
echo "The bass guitarist was $two, the drummer was $four";
// The bass guitarist was Paul, the drummer was Ringo

[ back to top ]

Loops

Loop a specified number of times
// Open a file for reading
$file = 'file.txt';
$fh = fopen($file, 'rb');

// Loop a specified number of times (100)
for ($i = 0; $i < 100; $i++) {
  // Read a line
  $line = fgets($fh);
  // If a line was read then output it
  if ($line !== false) {
    echo $line;
  }
}
While loop
// Loop as long as a condition is true
$x = 1; // Initialize a loop counter
while($x <= 5) { // Loop as long as $x is less than or equal to 5
  echo "The number is $x<br>";
  $x++; // Increase the loop counter value by 1 for each iteration
}
// The number is 1
// etc
// The number is 5

[ back to top ]

Patterns

Replace a pattern in a string:
// Example 1
// Pattern = a regular expression
$string = preg_replace('/pattern/', "new", $string);
// Example 2 - case insensitive
$string = eregi_replace('/pattern/', "new", $string);
Check for a (first) match in a string:
// Pattern = a regular expression
if (preg_match("/pattern/", $string)) {
// If a match was found
  // do something...
} else {
  // do something else...
}

[ back to top ]

Files

Create / delete files:
touch("myfile.txt"); // Create a file
unlink("myfile.txt"); // Delete a file
// Or
$filename = 'test.txt';
$handle = fopen($filename, 'w'); // For writing
fclose($handle);
Read and display the contents of a file:
// Example 1
if (file_exists($filename)) {
  $file_contents = file_get_contents($filename);
  echo $file_contents;
}
// Example 2
// Return an array with each line as an element
$fileArray = file("myfile.txt");
// Do something useful with the array
$file_contents = implode($fileArray);
echo $file_contents;
Write to a file:
$filename = "myfile.txt"; // File must be writable
$fp = fopen($filename, "w") or die("Error!");
fwrite($fp, "Some content to be written.");
fclose($fp);
// The above overwrites the whole file
// To append to the file, use "a" instead of "w"
List the contents of a folder:
$dirname = "path/folder/";
$dh = opendir($dirname);
while (false !== ($file = readdir($dh))) {
  if (is_dir("$dirname/$file")) {
    echo "(Folder) ";
  }
  echo "$file, ";
}
closedir($dh);
Output 'readdir' file list alphabetically:
$dirname = "path/folder/";
if ($folder = opendir($dirname)) {
  $filesArray = array();
  while (false !== ($file = readdir($folder))) {
    // Add each file to array
    $filesArray[] = $file;
  }
  // Sort array alphabetically
  natcasesort($filesArray);
  // Output list
  foreach ($filesArray as $file) {
    echo "$file, ";
  }
  closedir($folder);
}

[ back to top ]

PHP Superglobals (arrays)

$GLOBALS // Vars in the global scope of the script
$_SERVER // Headers, paths, and script locations
$_GET // Vars passed via URL parameters
$_POST // Vars passed via HTTP POST
$_FILES // Items uploaded via HTTP POST
$_COOKIE // Vars passed via HTTP Cookies
$_SESSION // Session vars
$_REQUEST // The contents of $_GET, $_POST and $_COOKIE
$_ENV // Deprecated
The '_SERVER' array:
if (!empty($GLOBALS['_SERVER'])) {
  $_SERVER_ARRAY = '_SERVER'; // $_SERVER_ARRAY is my var
} else if (!empty($GLOBALS['HTTP_SERVER_VARS'])) {
  $_SERVER_ARRAY = 'HTTP_SERVER_VARS';
} else {
  $_SERVER_ARRAY = 'GLOBALS';
} // HTTP_SERVER_VARS is deprecated
// Assign some variables
$serverName = ${$_SERVER_ARRAY}['SERVER_NAME'];
$httpHost = ${$_SERVER_ARRAY}['HTTP_HOST'];
$remoteAddreess = ${$_SERVER_ARRAY}['REMOTE_ADDR'];
$requestURI = ${$_SERVER_ARRAY}['REQUEST_URI'];
$scriptFilename = ${$_SERVER_ARRAY}['SCRIPT_FILENAME'];
$scriptName = ${$_SERVER_ARRAY}['SCRIPT_NAME'];
$phpSelf = ${$_SERVER_ARRAY}['PHP_SELF'];
// Outputs
$serverName // www.mini-print.com
$httpHost // www.mini-print.com
$requestURI // /file.php
$scriptFilename // /home/path/public_html/file.php
$scriptName // /file.php
$phpSelf // /file.php
Magic constants:
__DIR__ // /home/path/public_html/
__FILE__ // /home/path/public_html/file.php
dirname(__FILE__) // /home/path/public_html
basename(__FILE__) // file.php
basename(dirname(__FILE__)) // public_html
basename(getcwd()) // Current directory, eg: img

[ back to top ]

Functions

// Don't return a value
function writeName() {
  echo "John Lennon";
}
// Usage
echo "His name is ";
writeName(); // His name is John Lennon

// With parameters
function writeName($name) {
  echo "His name is ". $name;
}
// Usage
writeName("John Lennon"); // His name is John Lennon

// Return a value
function writeName($name) {
  $output = "His name is ". $name;
  return $output;
}
// Usage
echo writeName("John Lennon"); // His name is John Lennon

// With external variable
$name = "John Lennon";
function writeName() {
  global $name;
  echo "His name is $name";
}
// Usage
writeName(); // His name is John Lennon

// Return a value
function addnums($x,$y) {
  $total = $x + $y;
  return $total;
}
// Usage (eg: add 2 and 3)
addnums(2,3); // 5

// Truncate (shorten) a string to a set length
function truncate($string, $max = 100, $replacement = '') {
  $startpos = $max - strlen($replacement);
  return substr_replace($string, $replacement, $startpos);
}
// Usage (eg: shorten to 50 characters ending with '...')
if (strlen($string) > 49) {
  $string = truncate($string, 50, '...');
}

[ back to top ]

Objects

// Template doesn't change
class SimpleClass { // Object
  function Template() { // Method
    $sourceFile = $this->textFile; // Property
    echo 'Content: ';
    include($sourceFile);
    // Prints: 'Content: whatever is in textfile.txt'
  }
}

// Create a new object from Template class
// The class can be included here as a separate file
$instance = new SimpleClass();
$instance->textFile = "textfile.txt"; // Property
$instance->Template(); // Method

[ back to top ]

Other

Using the ternary operator:
(Condition) ? (if met) : (if not met);

// Example
$marks = 40; // 40 is the test data in this example
print ($marks >= 40) ? "pass" : "fail"; // pass
// If marks less than 40, fail

// Example
// $age is the variable in this example (eg: number entered in a form)
$status = ($age < 16) ? 'child' : 'adult';
// Is child if less than 16, otherwise is adult

// Example
// As a boolean
$adult = ($age > 16) ? TRUE : FALSE;
// If age is less than 16, adult is false
if ($adult) {
  etc.

// Comparison with the if statement
if ($age < 16) {
  $status = 'child';
} else {
  $status = 'adult';
}

[ back to top ]

Technical »

Page last modified: 07 August, 2020