The Blog of Ravi Gehlot

Jun 01

Quick Syntax intro to Object Oriented Programming (OOP) with PHP

This post is a quick reference from Chapter 6: Objects from “Programming PHP” a book published by O’REILLY and authored by Rasmus Lerdorf, Kevin Tatroe & Peter MacIntyre. It’s the 2nd Edition and it covers PHP5.

Why use Object Oriented Programming (OOP)?

Because it opens the door to cleaner designs, easier maintenance, and greater code re-useability. OOP acknowledges the fundamental connection between data and the code that works on that data, and it lets you design and implement programs around that connection. In a procedural programming language, each user would be a data structure, and there would probably be a set of functions that work with users’ data structures. In a object oriented programming language, each user would be an object—a data structure with attached code. The data and the code are still there, but they are treated as an inseparable unit. The object, as union of code and data, is the modular unit for application development and code reuse.

What is an object?

An object is an instance of a class. In this case, it’s an actual user data structure with attached code. Objects and classes are a bit like values and data types. There is only one integer data type, but there are many possible integers. Similarly, your program defines only one user class but can create many different (or identical) users from it. The data associated with an object are called its properties. The functions associated with an object are called its methods. When you define a class, you define the names of its properties and give the code for its methods.

How to create an object?

$object = new Class;

How to access properties and methods?

$object->propertyName;

$object->methodName(arg1, arg2…);

HTML::p(“Hello, world”); // this is how to access a static method

How to declare a class, a property and a method?

class className [ extends baseclass ] {

     $propertyName = value;

     function methodName(args) { // code }

}

How to declare constants?

class paymentMethod {

     const NUMBER = 1;

}

echo paymentMethod::NUMBER;

How to use inheritance?

To inherit the properties and methods from another class, use the extends keyword in the class definition, followed by the name of the base class:

class Person {

}

class Employee extends Person {

}

What are interfaces and how to declare them?

Interfaces provide a way for defining contracts to which a class adheres; the interface provides method prototypes and constants, and any class which implements the interface must provide implementations for all methods in the interface. Here’s the syntax for an interface definition:

interface interfaceName {

   function functionName();

}

interface Printable {

   function printOutput();

}

class imageContent implements Printable {

   function printOutput() {

        echo “print this”;

   }

}

What is an abstract class?

PHP also provides a mechanism for declaring that certain methods on the class must be implemented by subclasses — the implementation of those methods is not defined in the parent class. In these cases, you provide an abstract method; in addition, if a class has any methods in it defined as abstract, you must also declare the class as an abstract class.

abstract class component {

   abstract function printOutput();

}

class imageComponent extends component {

   function printOutput() {

       echo “pretty picture”;

   }

}

Abstract classes cannot be instantiated. Also note that unlike some languages, you cannot provide a default implementation for abstract methods.

What is a constructor?

Quite simple. A constructor will run automatically after a class has been instantiated. So basically, you don’t need to call constructor. It executes it right after the instantiation is complete.

class Person {

    function __constructor($name, $age) {

         $this->name = $name;

         $this->age = $age;

    }

}

What are destructors?

When an object is destroyed, such as when the last reference to an object is removed or the end of the script is reached, its destructor is called. PHP automatically cleans up resources at the end of script’s execution.

class building {

     function __destruct() {

         echo “A building is being destroyed!”;

     }

}

What is introspection?

Introspection is the ability of a program to examine an object’s characteristics, such as its name, parent class(if any), properties, and methods. With introspection, you can write code that operates on any class or object. You don’t need to know which methods or properties are defined when you write your code; instead, you can discover  that information at runtime, which makes it possible for you to write generic debuggers, serializes, profilers, etc.

- Examining Classes

To determine whether a class exists or not, use the class_exists() function, which takes in a string and returns a Boolean value. Alternatively, you can use get_declared_classes() function, which returns an array of defined classes and checks if the class name is in the returned array:

$yes_no = class_exists(className);

$classes = get_declared_classes();

You can get the methods and properties that exist in a class (including those that are inherited from superclasses) using the get_class_methods() and get_class_vars() functions. These functions take a class name and return an array:

$methods = get_class_methods(className);

$properties = get_class_vars(className);

- Examining an Object

To get the class to which an object belongs, first make sure it is an object using the is_object() function, and then get the class with the get_class() function:

$yes_no = is_object(var);

$className = get_class(object);

Before calling a method on an object, you can assure that it exists using method_exists() function:

$yes_no = method_exists(object, method);

Just as get_class_vars() returns an array of properties for a class, get_object_vars() returns an array of properties set in an object:

$array = get_object_vars(object);

And just as get_class_vars() returns only those properties with default values, get_object_vars() returns only those properties that are set:

What is Serialization?

Serializing an object means converting it to a bytestream representation that can be stored in a file. This is useful for persistent data; for example, PHP sessions automatically save and restore objects. Serialization in PHP is mostly automatic — it requires little extra work from you, beyond calling the serialize() and unserialize() functions:

$encoded = serialize(something);

$something = unserialize(decoded);

Serialization is most commonly used with PHP’s sessions, which handle the serialization for you. All you need to do is tell PHP which variables to keep track of, and they are automatically preserved between visits to pages on your site. However, sessions are not the only use of serialization — if you want to implement your own from of persistent objects, the serialize() and unserialize() functions are a natural choice.

May 29

NULL, NOT NULL and empty

NULL, NOT NULL and empty

A database architect may choose to set database columns to either NULL or NOT NULL. Why is this important? Well, it is important because it may have an impact in how you write your SQL statements. If the columns are set to allow NULL then you do not have to list all your columns on your INSERT statements. That’s because NULL means no need to insert a value. But if the columns are set to NOT NULL then you must write all your columns on your insert statements. On IF control structures, you may check against NULLS. It is important to know that NULL means that no “value” is there. There is nothing in that container. It is not even empty. It just does not exist. NULL means that it does not exist. You can set a field to empty by inserting an empty string. That would mean that something exists in that field (an empty space). It ceases to be nonexistent. It’s now a string with zero characters. Indeed, empty and NULL are not the same thing.

May 26

PHP Arrays Ex. #1: Simple Array

Let’s brief a bit on Arrays before moving on into this question. Please read the question at http://phpexercises.com/php-simple-array-exercise.html

There are two types of Arrays in PHP:

A Numerical or Indexed array will have numbers for it’s keys. So for example, $a[0] = ‘somebody’, $a[1] = ‘else’, $a[2] = ‘elsewhere’. So in this example we have a numerical key starting from 0 all the way to the number 2. That’s 3 records on the array. In the Associative Array, the key or indexer is a string and not a number. So an example would be something like $a[‘Ravi’] = ‘programmer’, $a[‘Gehlot’] = ‘last name’.

In this exercise, we are going to build an Associate Array with the weather conditions listed out. The exercise did not specify weather to use numerical or associative. The code below is what I came up with for an associative array:

<?php
$listWeatherConditions = array(‘rain’ => ‘rain’
                                ,    ’sunshine’ => ‘sunshine’
                                ,    ’clouds’ => ‘clouds’
                                ,    ’hail’ => ‘hail’
                                ,    ’sleet’ => ‘sleet’
                                ,    ’snow’ => ‘snow’
                                ,    ’wind’ => ‘wind’
                                );
?>
<!DOCTYPE html>
<html>
<head>
      <title>My Weather Condition Array page</title>
</head>
<body>
      <h3>My Weather Condition Array Page</h3>
<?php
echo ‘We've seen all kinds of weather this month. At the beginning of the month, we had ’ .
$listWeatherConditions[‘snow’] . ’ and ’ . $listWeatherConditions[‘wind’] . ‘. Then came ’ .
$listWeatherConditions[‘sunshine’] . ’ with a few clouds and some ’ . $listWeatherConditions[‘rain’] .
’. At least we didn't get any ’ . $listWeatherConditions[‘hail’] . ’ or ’ . $listWeatherConditions[‘sleet’] . ‘.’;
?>
</body>
</html>

The code below is what I came up with for a numerical array:

<?php
$listWeatherConditions = array(‘rain’, ‘sunshine’, ‘clouds’, ‘hail’, ‘sleet’, ‘snow’, ‘wind’);
?>
<!DOCTYPE html>
<html>
<head>
      <title>My Weather Condition Array page</title>
</head>
<body>
      <h3>My Weather Condition Array Page</h3>
<?php
echo ‘We've seen all kinds of weather this month. At the beginning of the month, we had ’ .
$listWeatherConditions[5] . ’ and ’ . $listWeatherConditions[6] . ‘. Then came ’ .
$listWeatherConditions[1] . ’ with a few clouds and some ’ . $listWeatherConditions[0] .
’. At least we didn't get any ’ . $listWeatherConditions[3] . ’ or ’ . $listWeatherConditions[4] . ‘.’;
?>
</body>
</html>

Go to http://phpexercises.com/php-simple-array-exercise.html to look at the original code answer from phpexercises.com. What I like about their code is that they took the time to write code comments. Comments are part of good code standards.

A few things about the ZEND Certification exam

In the study guide, they mention that REGISTER_GLOBALS and MAGIC_QUOTES_GPC must be set to off. So let’s go over what those are and why they might have wanted it to be set to off.

REGISTER_GLOBALS

    If OFF, *no* variables passed from $_GET, $_POST and $_COOKIES will be created in the global namespace. Here is an excerpt from IBM’s website:

register_globals is not, in and of itself, a security hazard. It does, however, make it harder to trace user input and harder to make sure your application is secure. Why does it do this? Because if register_globals is on, any variable passed to the PHP script by GET, POST, and COOKIE will be created in the global namespace, as well as in the $_GET, $_POST, or $_COOKIE arrays.

When is this useful or not? I don’t quite understand it. Any input is welcome.

MAGIC_QUOTES_GPC

     According to the PHP manual, magic_quotes_gpc() sets the state for GPC (Get/Post/Cookie) operations. When magic_quotes_gpc() is ON, all ’ (single-quote), ” (double quote), \ (backslash) and NUL’s are escaped with a backslash automatically. With magic_quotes_gpc() OFF, you have to learn about the addslashes() and stripslashes() functions in order to escape data yourself. However, the zend study guide doesn’t mention anything about data that comes from a database like MySQL or even an external script executed by exec(). For database, if magic_quotes_runtime is ON then data coming from the DB will be escaped. There might be a question on the exam about data coming from the database. That data would be escaped.

PHP Array question number #6 from phpexercises.com

There is a famous quote on practice that goes like this “Practice is the best of all instructors”. Practice is the best way to learn. In this post, we will solve a question from http://phpexercises.com/php-manipulate-array-exercise.html titled “PHP Arrays Ex. #6: Manipulate the Array”. I came up with my own version and then I compared it to what they had come up with. Then I went further into making it more presentable by changing a few things. Let’s go over it. First read the question from the website.

They want you to choose a spring month because spring months have 30 days. However, does this really matter? No. Why? Well, we know for sure that have 30 days to work with. That is all we need to worry about. You don’t have specify any month on your script. It’s just information to try to complicate more. Most questions become tricky when they try to throw useless information. To simplify it, don’t worry about Celsius temps. Just keep it simple. The temps are already in Fahrenheit so keep it that way. We already ruled out 2 pieces of unnecessary information. No month, no Celsius. The key to solving this problem lies on the second paragraph. You need to compute the average of all high temps. Remember, all of those temps are HIGH temps.  So to calculate the mean value(average) sum them up and divide by 30. Next, find the 5 warmest temps and the 5 coolest temps. You got 3 tasks to do on this question. Before coding, take a pen and a paper and do some brainstorming. I wrote down all the numbers that they mentioned on the question. I computed the average and then I re-arranged the values so that I could better see which ones were the highest numbers(warmest) and which ones were the lowest numbers(coolest). So right off the bat, you have the first answer. All you got to do is add and divide to get the average. Then for the other 2 answers, re-arrange(sort) the array so that you can pick the 5 lowest and 5 warmest temps. Job Done. After the initial brainstorming, we go into actual coding.

The code explains it all so take a look. If you don’t know what the functions do then consult the PHP manual. This is what I came up with on my own:

<?php
/*
PHP Arrays Ex. #6: Manipulate the Array

In this PHP exercise, you will create an array of temperatures. Choose a spring month to have a wider range of
temperatures to handle. We’ll use 30 days of the month. The exercise is generic, but feel free to use a specific
month in your own script. The answer script will use the Fahrenheit scale, but again feel free to use Celsius if you prefer.

Create your array of 30 high temperatures, approximating the weather for a spring month, then find the average
high temp, the five warmest high temps and the five coolest high temps. Print your findings to the browser.

Hint: the HTML character entity for the degree sign is &deg;.

Feel free to make up the temps or gather data for your own area. Here’s a list of thirty Fahrenheit high temperatures
you can use if you like:

68, 70, 72, 58, 60, 79, 82, 73, 75, 77, 73, 58, 63, 79, 78,
68, 72, 73, 80, 79, 68, 72, 75, 77, 73, 78, 82, 85, 89, 83
*/

// Create an array of temperatures for the month of March
$monthTemp = array(68, 70, 72, 58, 60, 79, 82, 73, 75, 77, 73, 58, 63, 79, 78, 68, 72, 73, 80, 79, 68, 72, 75, 77, 73, 78, 82, 85, 89, 83);

// Finding the average for high temp. Take all numbers and do the average.
    $count = count($monthTemp);
    $total = 0;
    for($a = 0; $a < $count; $a++) {
        $sum = $monthTemp[$a] . ‘<br />’;
        $total += $sum;
    }
    $average = $total / $count;
    echo ‘The average for high temp is ’ . $average . ’ &deg;F or ’ . round($average) . ’ &deg;F<br /><br />’;

// The five warmest high temps. 80, 82, 83, 85, 89. We know that the highest temperature is 89.
    // We sort the array to have the last 5 numbers be the warmest high temps.
    sort($monthTemp);
   
    // pop last 5 keys
    $highTemp5 = array_pop($monthTemp);
    $highTemp4 = array_pop($monthTemp);
    $highTemp3 = array_pop($monthTemp);
    $highTemp2 = array_pop($monthTemp);
    $highTemp1 = array_pop($monthTemp);
   
    echo ‘The five warmest high temps are: ’ . $highTemp5 . ‘&deg;F, ’ . $highTemp4 . ‘&deg;F, ’ . $highTemp3 . ‘&deg;F, ’ . $highTemp2 . ‘&deg;F, ’ . $highTemp1 . ‘&deg;F<br /><br />’;

// The five coolest high temps.    
    $coolestTemp5 = array_shift($monthTemp);
    $coolestTemp4 = array_shift($monthTemp);
    $coolestTemp3 = array_shift($monthTemp);
    $coolestTemp2 = array_shift($monthTemp);
    $coolestTemp1 = array_shift($monthTemp);
   
    echo ‘The five coolest high temps are: ’ . $coolestTemp5 . ‘&deg;F, ’ . $coolestTemp4 . ‘&deg;F, ’ . $coolestTemp3 . ‘&deg;F, ’ . $coolestTemp2 . ‘&deg;F, ’ . $coolestTemp1 . ‘&deg;F<br /><br />’;
?>

A bit more complicated than the original answer but I was able to get to the same answer like they did. Now look at the original answer from their site and compare it to mine:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
     “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
 
<html xmlns=”http://www.w3.org/1999/xhtml”  xml:lang=”en” lang=”en”>
<head>
<meta http-equiv=”content-type” content=”text/html;charset=iso-8859-1” />
<title>High Temperatures Array</title>
</head>
 
<body>
<h2>High Temperatures for Spring Month</h2>
 
<?php
//Create an array of 30 Fahrenheit high temperatures for a spring month.
$highTemps = array(
  68, 70, 72, 58, 60, 79, 82, 73, 75, 77, 73, 58, 63, 79, 78,
  68, 72, 73, 80, 79, 68, 72, 75, 77, 73, 78, 82, 85, 89, 83
);
 
//Get number of temps.
$count = count($highTemps);
 
//Get a total of all temps.
$total = 0;
foreach ($highTemps as $h){
  $total += $h;
}
 
//Calculate average.
$avg = round($total / $count);
 
//Send data to the browser. &deg; is the ASCII code for the degree sign.
echo “<p>The average high temperature for the month was $avg &deg;F.</p>\n”;
 
//Sort the temps and get the top and bottom five.
//Use rsort to produce a descending sort.
rsort($highTemps);
//Pull out the top 5 temps.
$topTemps = array_slice($highTemps, 0, 5);
echo “<p>The warmest five high temperatures were: <br />\n”;
foreach($topTemps as $t){
  echo “$t &deg;F <br/> \n”;
}
echo “</p>”;
  
//Pull out the bottom five temps.
$lowTemps = array_slice($highTemps, -5, 5);
echo “<p>The coolest five high temperatures were: <br/>\n”;
foreach($lowTemps as $l){
  echo “$l &deg;F <br/> \n”;
}
echo “</p>”;
 
?>
 
</body>
</html>

In trying to play with it and further my knowledge, I got rid of duplicates keys from the array, added averages for the 5 warmest and coolest temps and then made sure that the coolest temps printed ascending rather. But remember, this is not exactly what they asked of you to do. So it would have been wrong to give this as an answer.

<?php
/*
PHP Arrays Ex. #6: Manipulate the Array

In this PHP exercise, you will create an array of temperatures. Choose a spring month to have a wider range of
temperatures to handle. We’ll use 30 days of the month. The exercise is generic, but feel free to use a specific
month in your own script. The answer script will use the Fahrenheit scale, but again feel free to use Celsius if you prefer.

Create your array of 30 high temperatures, approximating the weather for a spring month, then find the average
high temp, the five warmest high temps and the five coolest high temps. Print your findings to the browser.

Hint: the HTML character entity for the degree sign is &deg;.

Feel free to make up the temps or gather data for your own area. Here’s a list of thirty Fahrenheit high temperatures
you can use if you like:

68, 70, 72, 58, 60, 79, 82, 73, 75, 77, 73, 58, 63, 79, 78,
68, 72, 73, 80, 79, 68, 72, 75, 77, 73, 78, 82, 85, 89, 83
*/

// Create an array of temperatures for the month of March
$monthTemp = array(68, 70, 72, 58, 60, 79, 82, 73, 75, 77, 73, 58, 63, 79, 78, 68, 72, 73, 80, 79, 68, 72, 75, 77, 73, 78, 82, 85, 89, 83);

// Finding the average for high temp. Take all numbers and do the average.
    $count = count($monthTemp);
    $total = 0;
    for($a = 0; $a < $count; $a++) {
        $sum = $monthTemp[$a] . ‘<br />’;
        $total += $sum;
    }
    $average = $total / $count;
    echo ‘The average for high temp is ’ . $average . ’ &deg;F or ’ . round($average) . ’ &deg;F<br /><br />’;

// The five warmest high temps. 80, 82, 83, 85, 89. We know that the highest temperature is 89.
    // We sort the array to have the last 5 numbers be the warmest high temps.
    sort($monthTemp);
   
    // We get rid of duplicated   
    $noDuplicates = array_unique($monthTemp);

    // pop last 5 keys
    $highTemp5 = array_pop($noDuplicates);
    $highTemp4 = array_pop($noDuplicates);
    $highTemp3 = array_pop($noDuplicates);
    $highTemp2 = array_pop($noDuplicates);
    $highTemp1 = array_pop($noDuplicates);
   
    echo ‘The five warmest high temps are: ’ . $highTemp5 . ‘&deg;F, ’ . $highTemp4 . ‘&deg;F, ’ . $highTemp3 . ‘&deg;F, ’ . $highTemp2 . ‘&deg;F, ’ . $highTemp1 . ‘&deg;F<br /><br />’;
    $warmestAverage = ($highTemp5 + $highTemp4 + $highTemp3 + $highTemp2 + $highTemp1) / 5;
    echo ‘The average of the five warmest high temps are: ’ . $warmestAverage . ’ &deg;F or ’ . round($warmestAverage) . ’ &deg;F<br /><br />’;

// The five coolest high temps.    
    $coolestTemp5 = array_shift($noDuplicates);
    $coolestTemp4 = array_shift($noDuplicates);
    $coolestTemp3 = array_shift($noDuplicates);
    $coolestTemp2 = array_shift($noDuplicates);
    $coolestTemp1 = array_shift($noDuplicates);
   
    echo ‘The five coolest high temps are: ’ . $coolestTemp5 . ‘&deg;F, ’ . $coolestTemp4 . ‘&deg;F, ’ . $coolestTemp3 . ‘&deg;F, ’ . $coolestTemp2 . ‘&deg;F, ’ . $coolestTemp1 . ‘&deg;F<br /><br />’;
    $coolestAverage = ($coolestTemp5 + $coolestTemp4 + $coolestTemp3 + $coolestTemp2 + $coolestTemp1) / 5;
    echo ‘The average of the five warmest high temps are: ’ . $coolestAverage . ’ &deg;F or ’ . round($coolestAverage) . ’ &deg;F<br /><br />’;
?>

May 25

FREE PHP Quizzes

If you know of any good FREE PHP quizzes please post a comment with a link to it.

Bitwise Operators: Studying for the ZEND PHP Certification

I was going to write a post on Bitwise Operators but I found a really good article written by Jim Plush that can be found at http://www.litfuel.net/tutorials/bitwise.htm He couldn’t have explained any better.

Recruiter asked me to take an ONLINE assessment test in PHP

Today I took an ONLINE assessment test in PHP from Proveit2.com(Kenexa Prove It! Skills Assessments). All questions were multiple choice questions with only one possible correct answer. I enjoy taking those assessments exams because it is another way to learn. On this post, I will try to comment on the test (what I can remember of it).

in_array()

    This function checks if a value exists on an array. If it finds a value, it returns boolean TRUE. If nothing is found, it returns boolean FALSE. The function itself is self-explanatory. The way that I like to remember this function is by asking myself the question “Is it in_array()?

PHP Magic Quotes

    Magic quotes, if enabled, will escape backslashes, double quotes and single quotes automatically. I know about Magic Quotes because I have been studying for the Zend PHP Certification; one of their requirements is that magic_quotes_gpc must be disabled. If enabled, Magic Quotes will automatically escape any incoming data like form submission. Magic Quotes is DEPRECATED according to the PHP manual. Another question on the exam had to do with how to strip out quotes. I am pretty sure that I got that one wrong because I was confused between the stripslashes() and addslashes() functions. The former is used to un-quote a quoted string while addslashes() will function the same way as PHP Magic Quotes.

ucwords()

    There can be no doubt as to what this function does. I mean, UC. stands for UpperCase and the plural of words gave it away that it had to uppercase more than one letter. For what I can remember, the tricky part of this question was the other functions in the multiple choice answers. They looked kind of similar but I shot for what seemed more appropriate. In all honest, I didn’t quite remember this one. It was a guess. Unlike strtoupper() that is used to uppercase an entire string, ucwords() will uppercase the first letter of each given word.

session_start() headers

    session_start() will initialize session data and send out several HTTP headers depending on the configuration. session_cache_limiter() can be used to control the following major headers Expires, Pragma and Content-Type. There are several other headers as well. The test concentrated in the above headers. For example, a session can be expired by sending a Expires header to the client causing him/her to log out. With the header Cache-Control one can allow/disallow the client to save information.

session_name()

   The session can be renamed using session_name() but it must be called before starting session_start(). Basically, you can rename a session and then expire the old one. I think that renaming it can avoid conflict. I never needed to rename a session so I am not sure how this would be useful.

lcfirst()

   Makes a string’s first character lowercase unlike strtolower() which lowercase the entire string. Again, the function is self-explanatory. lcfirst() stand for lower-case-only-first-character.

namespace identifier

    I have no experience with namespaces. But from looking at the answers, I could tell that this causes an error or warning. I took a good guess on this one. After the exam, I looked it up on the Internet and fair enough it does cause an error. But I do have to research on this one. All multiple choices answers had errors or warnings.

goto

   They gave a class with a method called goto. This would never work because goto is a reserved word. It’s a well known reserved word.

extension_loaded()

   It is possible to find out which extensions are loaded with using this function. However, I prefer phpinfo() because not only do you get to see your extensions but also almost every other important information.

REST

   This question asked what REST returned. It is XML, JSON.

constant table

    A constant table is a table that is:

  1. empty.
  2. has 1 row.
  3. a table that is used with the WHERE clause on an UNIQUE index or PRIMARY KEY where all INDEX parts are used in constant expressions and the index parts are defined as NOT NULL.

array_unique()

    This function will look for all duplicates and return a new array without any duplicated.

xml_parse_into_struct()

    This function is very much used. Parse XML data into an array structure.

mysql_field_seek()

    I never used it but it’s kind logical to think that it will seek a field in an array. Why? Well, mysql returns an array; arrays work with offsets. So logically this function had to seek an offset field. Now what it does with it or what not. That I have to look it up later.

number_format()

   This function will take a number and place commas where applies. So for example. If I give it 124987234, it should return 124,987,234.

round()

   In the exam, they wanted to know how to round down a number. In the multiple choice answers they had all kind of functions like round_down() and roundDown() so it was confusing. I chose round() because it was what I knew. In fact, round() will round it up or down. To my knowledge, there is no other function to do the same thing.

SOAP __doRequest

   The question had to do with what method performs a request when using SOAP. the answer was __doRequest. This was another good guess.

E_NOTICE

   This predefined constant will return run-time errors only. The function error_reporting() takes logical operators to return errors. So you can return E_NOTICE & E_ALL among other errors. This was easy!

substr() and strpos()

   I used a little bit of common sense on this question. substr() takes 3 parameters. That much I knew. So one of the answers was already cut out. Also the last 2 parameters of substr() takes only numbers. The second parameter is for position and the third one for length. With strpost(), we can can find the position. So with that, I ruled out another answer that had strpost() for length. With the 2 answers remaining, the length count for “true” could only be 4. I went for that answer.

date()

   This question shouldn’t have been there in the first place. The reason why I say this is because it’s a little too much to expect that a person can remember all the possible variations of lowercase and uppercase letters that when put together can give you the date specified. One thing I kind of noticed from working with date() is that usually lowercase letters represent numbers while uppercase letters represent strings. So I kind of took an estimated guess on this one.

strtotime() and idate()

    strtotime formats a date into number seconds. This is what we call UNIX timestamp format. With idate(), you can take an UNIX timestamp and return an integer number. I never used UNIX timestamps let alone idate. So I probably got this one wrong.

modulus operator

    There was a question with a modulus operator. Basically, they gave two integers and they asked for the result modulus of it. The result was 6. The modulus operator gives the reminder.

error control @ operator

    This operator suppresses any errors that may occur. So for example, in the test they had a variable inside of a string but that variable did not exist. it hadn’t been declared and set. Without the error control operator, it would have returned an error instead. But with the operator it suppresses the error and still prints part of the expression.

array_pop() and implode()

array_pop() was a tricky one because I never used it. I didn’t know it existed. So I took a guess on this one. But array_pop() will pop the last element of an array. implode() will join elements.

Apr 16

“Choose a job you love, and you will never have to work a day in your life.
Confucius”