PHP call_user_func vs just calling function

Always use the actual function name when you know it.

call_user_func is for calling functions whose name you don’t know ahead of time but it is much less efficient since the program has to lookup the function at runtime. Also useful if you don’t know how many arguments you are passing. call_user_func calls functions with a series of individual parameters.

call_user_func_array calls functions with array of parameters.

PHP ArrayAccess and ArrayObject

In very simple terms, ArrayAccess is an interface, which you can implement in your own objects; ArrayObject, on the other hand, is a class, which you can either use or extend.

ArrayAccess is an interface built in to PHP which lets you dictate how PHP behaves when an object has array syntax (square brackets) attached to it. Interfaces are collections of function prototypes that we can use as templates for our own code. If you read the manual page for ArrayAccess, it shows four functions:

ArrayAccess {
/* Methods */
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )

ArrayObject is an object, you can implement and extend it as you usually would. It implements a bunch of useful interfaces and wraps them up into an object. For creating an object to look a lot like an array, take a look at ArrayObject! It implements ArrayAccess as we saw above, but also Countable, Traversable, and others.

ArrayAccess vs ArrayObject

PHP Generators

Generators are functions that provide a simple way to loop through data without the need to build an array in memory. “yield” is the main command here.

function getRange ($max = 10) {
    for ($i = 1; $i < $max; $i++) {
        yield $i;

foreach (getRange(PHP_INT_MAX) as $range) {
    echo "Dataset {$range} 
"; }

Dissecting the getRange function, this time, we only loop through the values and yield an output. yield is similar to return as it returns a value from a function, but the only difference is that yield returns a value only when it is needed and does not try to keep the entire dataset in memory.

Why we use generators?
There are times when we might want to parse a large dataset (it can be log files), perform computation on a large database result, etc. We don’t want actions like this hogging all the memory. We should try to conserve memory as much as possible. The data doesn’t necessarily need to be large — generators are effective no matter how small a dataset is.

Generators can be key-value too :

function getRange ($max = 10) {
    for ($i = 1; $i < $max; $i++) {
        $value = $i * mt_rand();

        yield $i => $value;

Generators can also take in values. This means that generators allow us to inject values into them. For example, we can send a value to our generator telling to stop execution or change the output.

function getRange ($max = 10) {
    for ($i = 1; $i < $max; $i++) {
        $injected = yield $i;

        if ($injected === 'stop') return;

$generator = getRange(PHP_INT_MAX);

foreach ($generator as $range) {
    if ($range === 10000) {

    echo "Dataset {$range} 
"; }

SQL Brushup

Get employee details from employee table whose employee name are “John” and “Roy”
Select * from EMPLOYEE where FIRST_NAME in (‘John’,’Roy’)

Get employee details from employee table whose employee name are not “John” and “Roy”
Select * from EMPLOYEE where FIRST_NAME not in (‘John’,’Roy’)

Get employee details from employee table whose first name starts with ‘J’

Select * from EMPLOYEE where FIRST_NAME like ‘J%’

Get employee details from employee table whose first name contains ‘o’

Select * from EMPLOYEE where FIRST_NAME like ‘%o%’

Get employee details from employee table whose first name ends with ‘n’ and name contains 4 letters

Select * from EMPLOYEE where FIRST_NAME like ‘___n’ (Underscores)

Get employee details from employee table whose Salary between 500000 and 800000

Select * from EMPLOYEE where Salary between 500000 and 800000

Get employee details from employee table whose joining year is “2013”
SQL Queries in MySQL, Select * from EMPLOYEE where year(joining_date)=’2013′

Get database date
select now()

Get department wise average salary from employee table order by salary ascending
select DEPARTMENT,avg(SALARY) AvgSalary from employee group by DEPARTMENT order by AvgSalary asc

The MySQL HAVING clause is often used with the GROUP BY clause. When using with the GROUP BY clause, we can apply a filter condition to the columns that appear in the GROUP BY clause. If the GROUP BY clause is omitted, the HAVING clause behaves like the WHERE clause.

Notice that the HAVING clause applies the filter condition to each group of rows, while the WHERE clause applies the filter condition to each individual row.

Select department,total salary with respect to a department from employee table where total salary greater than 800000 order by Total_Salary descending
Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by DEPARTMENT having sum(SALARY) >800000 order by Total_Salary desc

Select employee details from employee table if data exists in incentive table ?
select * from EMPLOYEE where exists (select * from INCENTIVES)

Since MySQL does not support MINUS operator here is one way to do it
Instead of

SELECT x, y FROM table_a
SELECT x, y FROM table_b;

SELECT a.x, a.y
FROM table_a a LEFT JOIN table_b b
ON a.x = b.x AND a.y = b.y

Select 20 % of salary from John , 10% of Salary for Roy and for other 15 % of salary from employee table

Select Last Name from employee table which contain only numbers
Select * from EMPLOYEE where lower(LAST_NAME)=upper(LAST_NAME)

Yahoo Phone Interview

1) Write a function to accept seconds and print time in format hh:mm:ss
2) If the same function is to be used multiple times how would we optimize the code so that we don’t have to calculate it each time. (hint: use static)

function formatTime($seconds) {
    if !($seconds) {
        return "";
    static $timeArray = array();
    if (isset($timeArray[$seconds])) {
        echo "using cache\n";
        return $timeArray[$seconds];
    $origSeconds = $seconds;
    $hours = floor($seconds / 3600);
    $seconds = $seconds % 3600;
    $mins = floor($seconds / 60);
    $seconds = $seconds % 60;
    $ret = sprintf("%02d::%02d::%02d", $hours, $mins, $seconds);
    $timeArray[$origSeconds] = $ret;
    return ($ret);

3) Can cookies be stolen ?
Yes cookies can be stolen. XSS is one way to do it.

4) Interface vs Abstract class
5) When does the page on screen get refreshed ?
Repainting and Reflowing

Function overloading in Javascript

Unique things about arguments in functions in Javascript:

1) You can pass any number of parameters to a function without causing an error.
2) You can also pass in no arguments but still make use of arguments inside the function (through arguments array)
3) you have access to arguments[0], arguments[1] etc in a function
4) arguments.length will give you number of parameters passed in. This is the way you can achieve function overloading. Based on number of parameters you do one thing or the other.
5) If you define multiple functions with same name, the one which is defined last will override all others.

Identifying Primitive and Reference Types in Javascript

5 Primitive Types: Number, Boolean, String, Null, Undefined

typeof “abc” => string
typeof “true” => boolean
typeof will work for mostly all of above except null.
typeof null will return “object”.
So to verify “null” just compare to null. (value == null)

6 Reference Types: Function, Object, Array, Date, Error, RegExp

typeof object will be “object”
typeof function will be “function”

for all the rest use instanceof to identity

items instanceof Array

Note that items instanceof Object will also return true since instanceof can identity inherited types.

For Array, if you are using frames and communicating values between frames then instanceof may not provide accurate results if you are checking instanceof. Its recommended to use Array.isArray(items) in that case.

Find kth largest element in an unsorted array

Method 1 (Simple Solution)
A Simple Solution is to sort the given array using a O(nlogn) sorting algorithm like Merge Sort, Heap Sort, etc and return the element at index k-1 in the sorted array. Time Complexity of this solution is O(nLogn).

Method 2 (QuickSelect)
Using technique similar to quicksort.
Complexity is O(n^2) but avg case is O(n)

Method 3 (Using Min Heap – HeapSelect)
We can find k’th smallest element in time complexity better than O(nLogn). A simple optomization is to create a Min Heap of the given n elements and call extractMin() k times.

Longest Substring between 2 Strings

1) Make a matrix m x n where m = string1 length and n = string2 length
2) if str1[i] != str2[j] then put matrix element as 0
3) if str1[i] == str2[j] then put matrix element as 1 + previous diagonal element. set max
4) form the longest substring by examining max element in matrix and going back diagonally to collect previous characters

$str1 = "GeeksForGeeks";
$str2 = "AllGeeksQuiz";
$len1 = strlen($str1);
$len2 = strlen($str2);
$matrix = array();
$max = 0;
for ($i = 0; $i < $len1 ; $i++) {
    for ($j = 0; $j < $len2 ; $j++) {
        if ($str1[$i] == $str2[$j]) {
            if (($i == 0) || ($j == 0))
                $matrix[$i][$j] = 1;
                $matrix[$i][$j] = $matrix[$i-1][$j-1] + 1;
            if ($matrix[$i][$j] > $max) {
                $maxI = $i;
                $maxJ = $j;
                $max = $matrix[$i][$j];

if ($max > 0) {
    $substring = '';
    for ($k = 0; $k < $max ; $k++) {
        $substring = $str1[$maxI-$k] . $substring;
    echo "Longest Substring: $substring\n";
} else {
    echo "No substring\n";

Generate Prime Numbers in the 1..x range

Generate Prime Numbers in the 1..x range.

/* Generate a prime list from 0 up to n, using The Sieve of Erantosthenes
param n The upper bound of the prime list (including n)
param prime[] An array of truth value whether a number is prime

void prime_sieve(int n, bool prime[]) {
  prime[0] = false;
  prime[1] = false;
  int i;
  for (i = 2; i <= n; i++) {
    prime[i] = true;
  int limit = sqrt(n);
  for (i = 2; i <= limit; i++) {
    if (prime[i]) {
      for (int j = i * i; j <= n; j += i)
        prime[j] = false;