Subhash AKA “CodeKadiya” is a Software Engineer who is specializing in Web technologies. He has over 7 years of experience in PHP both in industry and freelance work providing web-based solutions for a wide range of clients from many parts of the world. His expertise in programming spans into XHTML/CSS, Apache, MySQL, Javascript/jQuery and AJAX technologies as well. During the past couple of years he has been developing web applications using popular industrial PHP frameworks such as Symfony, CodeIgniter and Zend. He is a FOSS enthusiast and currently employed at Latitude655. Subhash developed a passion for programming at the age of 13 and his swift efficient coding was appreciated by the community of Codewalkers.com. Subhash obtained his Bachelors degree from British Computer Society (BCS). He is currently engaged in a Masters in IT at University of Colombo. He draws extreme pleasure out of listening to music at all times including when he is programming.
 

PHP

10/29/2009 1:42 am By Subhash Vithanapathirana | Articles: 9

Welcome back! Last month's article was all about creating forms and handling/processing the user input using PHP. Assuming it is clear, today we are moving towards the in-built functions of PHP. At the end of the today's article I hope it will open new openings for your imagination since there is no limit to the possibilities of using functions in PHP. So keep focused...

 

Introduction

Hopefully you can remember in our September article while we discussed about user defined functions, I mentioned that PHP has a numerous number of in-built or language defined functions. That is what we're about to discussion today. As you already know, function can accept one or more parameters and provide you with a processed result, without having to worry about the internal logic of it. PHP is a function rich language and you will be amazed to find a function for almost any commonly occurring task while you're writing a code. This is one of the reasons for the real power of PHP. These functions make your coding life more enjoyable, less lengthy codes, less time consumption and more readable.

In PHP, there are over 700 functions as per version 5.2 and these can be categorized based on the type of data they work on and what type of tasks they are used for. To name a few; Array functions, Date functions, File system functions, Math functions, String functions etc. My objective of taking PHP in-built functions as the topic is not to explain all the functions in PHP language. It is almost an impossible task which could take ages. Therefore, what I intend is to give you the feel of how to find and use a function whenever you are in a situation to use one. I will be outlining few commonly used functions from above mentioned categories in today's article for you to get an idea.

 

Array functions

array — Create an array

count — Count all elements in an array, or properties in an object

sort — Sort an array

rsort — Sort an array in reverse order

shuffle — Shuffle an array

array_sum — Calculate the sum of values in an array

array_search — Searches the array for a given value and returns the corresponding key if successful

in_array — Checks if a value exists in an array

array_keys — Return all the keys of an array

array_unique — Removes duplicate values from an array

Examples:

<?php
$myArray 
= array("Laptop"=>150000,"Mobile Phone"=>43000,"Webcam"=>5000);
$count count($myArray); // 3
sort($myArray); // sorts the array in ascending order by value
rsort($myArray); // sorts the array in descending order by value
shuffle($myArray); // shuffles the array in random order
$cost array_sum($myArray); // 198000
$searchKey array_search(43000$myArray); // returns the position of 43000 in array
$check in_array(2000$myArray); // returns false since 2000 is not found in array
$keys array_keys($myArray); // returns a new array containing only the keys of $myArray
$uniqueArray array_unique($myArray); // removes any duplicate values of array
?>

 

Date/Time functions

 

date — Format a local time/date

time— Return current Unix timestamp

strtotime — Parse about any English textual datetime description into a Unix timestamp

mktime — Get Unix timestamp for a date

Examples:

<?php
date
("Y-m-d"); // returns the current date in given format; 2009-10-18
time(); // returns the current timestamp; 1255840654
strtotime("2009-02-15 16:55:00"); // returns the timestamp of given date (in any format); 1234697100
mktime(00012321997); // returns the timestamp of given date; 883591200
?>

 

File system functions

fopen — Opens file or URL

fread — Binary-safe file read

fwrite — Binary-safe file write

filesize — Gets file size

filetype — Gets file type

fclose — Closes an open file pointer

copy — Copies file

rename — Renames a file or directory

unlink — Deletes a file

Examples:

<?php
$filename 
"something.txt";
$size filesize($filename);
$fp fopen($filename"w");
$content fread($fp$size);
fclose($fp);

copy($filename"something_copy.txt");
unlink($filename);
?>

 

Math functions

max — Find highest value

min — Find lowest value

pow — Exponential expression

sqrt — Square root

round — Rounds a float

rand — Generate a random integer

base_convert — Convert a number between arbitrary bases

Examples:

<?php
$max_val 
max(5,42,6,20,5,7,83,2,6,48,9,32); // 82
$min_val min(5,42,6,20,5,7,83,2,6,48,9,32); // 2
$num pow(2,8); // 256
$sq sqrt(16); // 4
$no round(3.4612,1); // 3.5
$random rand(0,100); // random number between 0 and 100
$base10 base_convert(1010111210); // 87
?>

 

String functions

trim — Strip whitespace (or other characters) from the beginning and end of a string

strlen — Get string length

substr— Return part of a string

strtoupper — Make a string uppercase

strtolower — Make a string lowercase

strpos — Find position of first occurrence of a string

str_replace — Replace all occurrences of the search string with the replacement string

implode — Join array elements with a string

explode — Split a string by string

md5 — Calculate the md5 hash of a string

Examples:

It is very important to note that what I explained above is only a handful of functions in PHP. There are lot of resources available in the Web for you to find out the functions and their usage. The official site PHP.net has complete support to all the functions http://php.net/quickref.php

I will be making use of different functions in my next set of articles so that all of you can get familiar with them more in future. Till then, it is recommended for you to try out a few from this list and strengthen your knowledge. Happy coding!

 

Previous Article

Share/Save
Your rating: None Average: 5 (1 vote)

Post new comment