Some logical interview questions & solutions

Below are some interview questions that usually asked during the technical interview if you are invited as a Sr. Developer.

 

These are very simple but it is always advice to read/learn and prepare yourself for interview.

 

These interview questions are just for checking your logic instead what you have done in your previous experience and how much strong you are in your programming language.

 

Hope these will help you a lot.

 

Questions are as below.

  1. How to get sum of diagonal elements of a symmetrical array using a single loop?
  2. How to check whether the string is palindrome or not?
  3. How to insert an element in linked list?
  4. Find the largest decreasing order array/series or sequence from a given array.

 

Try yourself once, if you need help scroll the page down 🙂

 

How to get sum of diagonal elements of a symmetrical array?
(Symmetrical array is an array that have same number of columns and rows)

[php]
<?php
$array = array(
0=>array(4,5,6,2),
1=>array(1,2,3,1),
2=>array(2,2,2,5),
3=>array(2,2,2,2)
);

echo "<pre>";
print_r($array);
echo "</pre>";

echo "<br />";
echo "The array have ".count($array)." rows.";
echo "<br />";
echo "The array have ".count($array[0])." columns";
echo "<br />";
echo "The array have ".(count($array,COUNT_RECURSIVE) – count($array))." elements";
echo "<br />";

$sum_diagonal_element = 0;
for($i=0,$j=0; $i < count($array); $i++){

if($i==$j){
$sum_diagonal_element += $array[$i][$j];
}
$j++;
}
echo "<br />";
// SUM OF A DIAGONAL ELEMENTS
echo $sum_diagonal_element;

// —–
$sum_both_diagonal_element = 0;
$coloumns = count($array[0]);
$sum_common = 0;

for($i=0,$j=0; $i < count($array); $i++){
$coloumns–;
if($i == $j){
$sum_both_diagonal_element += $array[$i][$j];
if($j != $coloumns){ // skip the common elements
$sum_both_diagonal_element += $array[$i][$coloumns];
}
}
$j++;
}
echo "<br />";
// SUM OF A BOTH DIAGONAL ELEMENTS
echo $sum_both_diagonal_element;

?>
[/php]

 

How to check whether the string is palindrome or not?
(Palindrome means that it’s (string) reverse will remain same as it is)

[php]
<?php
$string = "SCRIPTARTICLE-ELcITRATPIRCs";

$newstring = "";
for($i = strlen($string)-1; $i >= 0; $i–){

$newstring .= $string[$i];
}

// It is better to change the case of string characters
if(strtolower($string) == strtolower($newstring)){
echo "String is palindrome!";
}else{
echo "String is not palindrome!";
}
?>
[/php]

 

How to insert an element in linked list?

[php]
<?php
class LinkedObject
{
var $value;
var $prev;
var $next;

public function __construct($value, $prev = null, $next = null)
{
$this->value = $value;
$this->prev = $prev;
$this->next = $next;
}

public function append(LinkedObject $insertee)
{
$link = $this;
while($link->next != null)
$link = $link->next;

$link->next = $insertee;
$insertee->prev = $link;
}

public function __toString()
{
$str = $this->value;
if($this->next != null)
{
$str .= " » ";
$str .= $this->next;
}
return $str;
}
}

$head = new LinkedObject("foo");
$head->append(new LinkedObject("bar"));
$head->append(new LinkedObject("baz"));
$head->append(new LinkedObject("mahi"));
echo $head . "\n"; // output is "foo » bar » baz » mahi"
?>
[/php]

 

Find the largest decreasing order array/series or sequence from a given array.

[php]
<?php
$array = array(10,9,8,5,17,16,15,25,24,23,22,21,20,19,14,13,12,34,33,90);

$mycount = 0;
$arr_desc_order = array();

for($i=0; $i < count($array); $i++){

if($i == 0){
$arr_desc_order[$mycount][] = $array[$i];
}else{
if($array[$i-1] < $array[$i]){
$mycount++;
}
$arr_desc_order[$mycount][] = $array[$i];
}

}

// Find the array with maximun number of elements
$arr_elemt = $count= 0;
foreach($arr_desc_order as $arr){
if(count($arr) > $arr_elemt){
$arr_elemt = $count;
}
$count++;
}

echo "<pre>";
print_r($arr_desc_order[$arr_elemt]);
echo "</pre>";
?>
[/php]

 

Hope the above will help you to crack the interview.
Best of luck!!

PHP Object cloning using clone keyword and __clone() magic method

Object cloning or clone of an object means to create a duplicate of an object.
With regular variables $var1 = $var2 means that a new variable $var1 created and have the value of $var2 that means 2 variables created.

 

With objects $obj2 = $obj1 does not mean that a new object i.e. $obj2 get created.

 

When we execute $obj2 = $obj1, the reference of $obj1 is assigned to $obj2. This means that $obj1 and $obj2 point to the same memory space.

So assigning other variables to an object will not actually copy the object, it will simply create a new reference to the same object. In order to truly copy an object, we must use the clone keyword.

[php]
<?php

class House {
private $room_name;

public function setRoomName($room_name) {
$this->room_name = $room_name;
}

public function getRoomName() {
return $this->room_name;
}
}

$obj1 = new House();
$obj1->setRoomName("Bedroom");

$obj2 = $obj1; //only reference or memory assigned

$obj2->setRoomName("Dining Room");

echo $obj1->getRoomName();
echo $obj2->getRoomName();

?>
[/php]

Both will return “Bedroom”

Therefore, to create a new $obj2 object we must “clone” an object to create a new object.

[php]
<?php
$obj2 = clone $obj1;
?>
[/php]

 

After the above line is executed $obj2 with a new memory space is created with the data members having the same value as that of $obj1. This is also referred to as shallow copy.

 

However, this technique will not work with a class that has a data member which is an object of another class (i.e object of an object technique is used). In such a scenario, the cloned object continues to share the reference of the data member object of the class that was cloned.

 

For resolving this we need to use the concept of ‘deep copy’ as opposed to ‘shallow copy’. To implement this you should implement the magic method __clone().

[php]
<?php

class House {
private $room_name;

public function setRoomName($room_name) {
$this->room_name = $room_name;
}

public function getRoomName() {
return $this->room_name;
}

public function __clone() {
$obj = new House();
$obj->setRoomName($this->room_name);
return $obj;
}

}

$obj1 = new House();
$obj1->setRoomName("Bedroom");

$obj2 = clone $obj1; //new object $obj2

$obj2->setRoomName("Dining Room");

echo $obj1->getRoomName();
echo $obj2->getRoomName();

?>
[/php]

 

So, the __clone() magic method allows developers to implement a deep copy of an object when it is cloned.

PHP first performs a shallow clone and the calls the __clone() method on the new object, if it exists, to complete the cloning process.

 

PHP Magic Predefined Constants & usages

PHP Magic Predefined Constants & usages

In PHP, a constant is a name or an identifier for a simple value. A constant name starts with a letter or underscore can be followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.

 

You have to use define() function to put value in the constant and for retrieval the value simply specifying the name.
The constant() function can be used if you create the constant name dynamically and want to fetch the value of the constant.

 

[php]
<?php
define("SITENAME", ‘scriptarticle.com’);
echo SITENAME;
echo constant("SITENAME"); // returns the same as previous one
?>
[/php]

 

Along with the above PHP itself have a lot of predefined constants.

Some of the constants that are specials and can be called as magical are listed as below with example, these starts and ends with double underscore (__) and written in capital letters.

The predefined constants are very useful to access information about your code.

 

__LINE__

returns the line number in the code where the constant appears.

 

__DIR__

represents the path to the current file.

 

__CLASS__

returns current class name.

 

__FUNCTION__

returns current function name.

 

__METHOD__

represents the current method name.

 

__NAMESPACE__

returns the current namespace name.

 

__FILE__

represents the name of your file, includes its full path.

 

I have included all these in the below example, have a look.

[php]
<?php

// Set namespace (works only with PHP 5.3 and later)
namespace Scriptarticle;

// this echo current file’s full path and name
echo "This file full path and file name is ‘" . __FILE__;

// this echo file full path
echo "This file full path is ‘" . __DIR__;

// This echo current line number on file
echo "This is line number " . __LINE__;

function function_magic_constant() {
echo "This is from ‘" . __FUNCTION__ . "’ function.";
}

// echo function and used namespace
function_magic_constant();

class SAConstants {
// echo class name
public function printClassName() {
echo "This is " . __CLASS__ . " class";
}
// echo class and method name
public function printMethodName() {
echo "This is " . __METHOD__ . " method";
}
// echo function name
public function printFunction() {
echo "This is function ‘" . __FUNCTION__ . "’ inside class";
}
public function printNamespace() {
echo "Namespace name is ‘" . __NAMESPACE__ . "’";
}
}

// create a object of the class
$obj = new SAConstants;

$obj->printClassName();

$obj->printMethodName();

// this prints function name inside class and used namespace
// same as method name, but without class
$obj->printFunction();

// this prints namespace name
$obj->printNamespace();

?>
[/php]

 

If you want to view a complete list of PHP predefined constant then follow the below links.

PHP Config Predefined Constants
PHP Image Predefined Constants
PHP Date Predefined Constants
PHP Core Predefined Constants
PHP Magic constants

 

Hope you have enjoyed the post!!

 

A Quick view on PHP magic methods

Magic Methods in PHP

(PHP Magical Reserved Functions Starts with double underscore)

According to me you all have heard about the PHP Magic methods.
You have also used some of these like __autoload and __construct.

 

Let’s have a quick view on magic methods, as sometimes it looks like it will hard to use these function but reality is these are very simple.
First of all let me tell what magic method is and why these are called magical? Are these methods really showed some type of magic as the name imply.

 

PHP reserves all function names starting with two underscore prefix (__) as magical.

Magic methods provide hooks into special PHP behavior.

 

PHP does not provide the definitions of the magic functions and the programmers have to write/code that what these functions will do. Magic functions will never directly be called by the programmer but PHP will call the function ‘behind the scenes’. That’s why they are called ‘magic’ functions because these can not be directly called and they allow the programmer to do some powerful things by the coding. I think it’s enough; you will be clearer by examples.

 

__autoload()
This is not a magic method exactly but it is very useful. The __autoload() function is automatically called when a class is instantiated and file will get include in the code. This is useful since you don’t always want to load every class again and again and add just in case you need it to add.

 

__construct()
This magic methods is called when user create object (instances of your class) of the class. Usually this is used for creating constructor in php5.

 

__destruct()
As the name implies, the __destruct() method is called when the object is destroyed by PHP’s garbage collector. It accepts no arguments, and it is usually used to perform memory clean-up operations such as closing a database connection or closing any file.

[php]
<?php

class House{

public function __construct() {
$this->created = time();
$this->logfile = fopen(‘/tmp/log.txt’, ‘w’);
}

public function __destruct() {
fclose($this->logfile);
}
}
$home = new House;
echo $home->created;
?>
[/php]

 

__get
This method is called when your object try attempt to read property or variable of the class which is unavailable or inaccessible.

 

__set
This method called when object of your class attempts to set value of the property which is inaccessible or unavailable in your class.

 

__call
This magic method trigger when you are attempting to call method or function of the class which is either inaccessible or unavailable.

 

__callstatic
This is same as __call executes when inaccessible or unavailable method in static context.

[php]
<?php

class House
{
function __get($name)
{
echo "__get executed as $name is unavailable";
}
function __set($name , $value)
{
echo "__set executed as $name not exists or inaccessible";
}
function __call($name , $parameter)
{
$a = print_r($parameter , true); //taking recursive array in string
echo "__call executed with name $name , parameter $a";

}
static function __callStatic($name , $parameter)
{
$a = print_r($parameter , true); //taking recursive array in string
echo "__callStatic executed with name $name , parameter $a";

}
}
$a = new House();
$a->abc = 3;//__set executed
$app = $a->myvar;//__get triggerd
$a->getMyinfo(‘mahesh’ , ‘scriptarticle’, ‘blog’);//__call willl executed
House::xyz(‘1’ , ‘sca’ , ‘help’);//__callstatic will executed

?>
[/php]

 

__isset
This magic methods called when isset() function is applied on a property of the class which is inaccessible or unavailable.

 

__unset
This is just opposite of isset method as it called when unset() function called on inaccessible or unavailable property of the class.

[php]
<?php

class House
{
function __isset($name)
{
echo "__isset is called for $name is unavailable";
}
function __unset($name)
{
echo "__unset is called for $name";
}
}
$a = new House();
isset($a->myvar);
unset($a->yourvar);

?>
[/php]

 

__sleep
This method will trigger when you are going to serialize your class’s object.

__wakeup
This will execute when you are un-serializing any class object.

[php]
<?php

class House {
public $name;
public $width;
public $data = array(); // stores misc. data in an array
public $connection; // holds some connection resource

public function __sleep() {
// list the properties to save
return array(‘name’, ’56’, ‘data’);
}

public function __wakeup() {
// reconnect to the house
$this->connect();
}
}
?>
[/php]

 

__toString
This executes when you are using echo on your object.

__invoke
This will trigger when you are using object of your class as function.

[php]
<?php

class House
{
public $myvar;

public function __construct($myvar)
{
$this->myvar = $myvar;
}

public function __toString()
{
return $this->myvar;
}

public function __invoke($x)
{
var_dump($x);
}
}

$object = new House(‘Hello’);
echo $object; // __toString will called
$object(8); // __invoke called
?>
[/php]

 

I have still left some magic methods as __clone(),__set_state() I’ll post a new article for these very soon.

Hope the above one helps you a lot.

 

WordPress .htaccess on Zeus Server Rewrites

WordPress .htaccess on zeus server rewrites (rather than Apache)

Yesterday, I got luck to transfer a WordPress website from one hosting to another.

 

The New hosting provider is http://www.names.co.uk and what I have found is it provides the web server Zeus instead of Apache as always I have worked on.

 

It is really a new experience for me as I have not worked on Zeus server before that.
Let’s discuss what is the main issue I have faced as WordPress move is not a difficult task.

 

You have to export import database and the path updates in database it’s very quick by following some simple queries.

move your wordpress site to a new domain – easy wordpress migration

And the other is just need to transfer files and need to update “wp-config.php”.

That’s it!

 

But what I have faced is, Zeus not supports mod_rewrite as this is a module for Apache servers.
So, Zeus doesn’t support .htaccess files which are required to make your site’s URLs look pretty and SEO friendly (WordPress with its Permalinks).

The file that you need to create is called rewrite.script and is Zeus equivalent to Apache’s .htaccess file.

 

Follow the below steps to work your WordPress site smoothly with permalinks.

The .htaccess File for default WordPress looks like this:

 

[sourcecode language=”plain”]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
[/sourcecode]

 

Zeus equivalent rewrite.script File

 

[sourcecode language=”plain”]
RULE_0_START:
# get the document root
map path into SCRATCH:DOCROOT from /
# initialize our variables
set SCRATCH:ORIG_URL = %{URL}
set SCRATCH:REQUEST_URI = %{URL}

# see if theres any queries in our URL
match URL into $ with ^(.*)\?(.*)$
if matched then
set SCRATCH:REQUEST_URI = $1
set SCRATCH:QUERY_STRING = $2
endif
RULE_0_END:

RULE_1_START:
# prepare to search for file, rewrite if its not found
set SCRATCH:REQUEST_FILENAME = %{SCRATCH:DOCROOT}
set SCRATCH:REQUEST_FILENAME . %{SCRATCH:REQUEST_URI}

# check to see if the file requested is an actual file or
# a directory with possibly an index. don’t rewrite if so
look for file at %{SCRATCH:REQUEST_FILENAME}
if not exists then
look for dir at %{SCRATCH:REQUEST_FILENAME}
if not exists then
set URL = /index.php?q=%{SCRATCH:REQUEST_URI}
goto QSA_RULE_START
endif
endif

# if we made it here then its a file or dir and no rewrite
goto END
RULE_1_END:

QSA_RULE_START:
# append the query string if there was one originally
# the same as [QSA,L] for apache
match SCRATCH:ORIG_URL into % with \?(.*)$
if matched then
set URL = %{URL}&%{SCRATCH:QUERY_STRING}
endif
goto END
QSA_RULE_END:
[/sourcecode]

 

You can also download the “rewrite.script” file by the below URL.

Download rewrite.script file

Upload “rewrite.script” file to your WordPress root folder (the same folder that contains wp-config.php).

 

If your WordPress site in installed in a sub folder, update line 27 and include the folder to the path before /index.php.

Next you will have to go into the WordPress Settings > Permalinks and save your permalink choice again. This will force WordPress to rebuild the permalinks for the site.

 

You can safely delete the .htaccess file from the remote site as it is no longer needed.

 

I think your site is working now fine but you may notice that you have index.php at the start of all your URLs.
Go to the WordPress settings > Permalinks and update that to a custom structure permalink:

/%category%/%postname%/

 

I think it all works, if you still face any issue post your comments below.

What is a WordPress Child theme & how to customize WordPress Theme using WordPress Child theme?

We all know that a WordPress theme is a collection of template files which lets us change the user interface, design, look & feel of the site.

 

Have you created WordPress theme or have installed any free theme or commercial one, many of you have done this job and have also customized but the problem is created when you have customized the original theme files and the update of that theme is available and you never would like to update as your customization will get destroyed if you update that, but my recommendation is that you should always keep your plugins and themes updated to the latest version. So you should take care during the customization and never do the customization in original file and should create a child theme. But what does that mean, and how do you do it?

 

In WordPress 3. 0 or latest versions a new concept was added by WordPress core team and community named as “Child Theme”.

 

As per the WordPress Codex definition of Child Theme:

 

“A WordPress child theme is a theme that inherits the functionality of another theme, called the parent theme. 

Child theme allows you to modify, or add to the functionality of that parent theme. A child theme is the safest and easiest way to modify an existing theme, whether you want to make a few tiny changes or extensive changes. Instead of modifying the theme files directly, you can create a child theme and override within. “

 

How to work with WordPress Child Theme?

 

Let’s take an example; I’ll create a child theme for WordPress default ‘Twenty Twelve’ theme.

1) So in this case, to create a child theme, I have to create a new directory alongside the ‘Twenty Twelve’ theme’s directory called twentytwelve-child.
“twentytwelve-child” directory should be in parallel of original theme twentytwelve.

2) Create a style.css file under the ‘twentytwelve-child’ theme directory.

Put the below text in style.css file

[css autolinks=”false” classname=”myclass” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”true” title=”example-filename.php”]
/*
Theme Name: Twenty Twelve Child
Theme URI: http://wp. tutsplus.com/
Description: Child theme for Twenty Twelve
Author: Japh
Author URI: http://wp. tutsplus.com/author/japh
Template: twentytwelve
Version: 1. 0. 0
*/

// This @import line loads the stylesheet of parent theme
@import url(‘. . /twentytwelve/style.css’);

//Theme customization starts here
[/css]

There are two important parts here to notice:

Template: twentytwelve
It tells WordPress that this theme is a child theme of the ‘Twenty Twelve’ theme

@import url(“. . /twentytwelve/style.css”);
It loads the parent theme’s (twentytwelve in this case) style.css as a starting point

3) Now you can log into your WordPress dashboard and see your ‘Twenty Twelve Child’ theme there, and activate it.

4) Make further alterations & addition and you will found that these will automatically reflected on your website.

 

Just Done!!

 

Now always keep in mind that whenever you want to make a customization to your theme, does it in your child theme.

Files in your child theme override files of the same name in the parent theme. So any file from your parent theme you want to change, copy to your child theme & make your modifications there.

The same goes for any templates that may not be in your parent theme. You can add them in your child theme, and WordPress will use them.

One exception to these rules is the functions.php file. In this case, the functions.php file for the child theme is loaded first, followed by the functions.php file of the parent theme. So there’s no need to copy the functions.php file from the parent into the child, just start fresh in the child theme for that one.

This allows the child theme to have all the functionality from the parent theme. Parent themes can also make their function pluggable, which allows a child theme to override them.

 

Why should you use WordPress Child Themes?

 

1. Safe Updates

A child theme automatically inherits the parent theme’s features, styles, and templates. This allows you to make changes to your site using child themes without ever modifying the parent theme. When a new version of the parent theme available, you can safely update it as you know that all your modifications are saved in the child theme.

 

2. Easy to Extend
A child theme built on a powerful theme framework allows a great deal of flexibility without writing a lot of code. You can selectively modify only the template files and functions that you need without going through other template files. You can add new functionality and much more.

 

3. Fall-back Safe
When you are creating a complete theme you need to think about all the possible scenarios and code for them. However, when you are working on a child theme and you forget to code for something, then there is always the parent theme’s functionality available as the fallback option.

 

WordPress catchable Tools for Child Theme

 

One-Click Child Theme plugin built and tested for the latest WordPress 3.x version.It adds a menu link into your Admin “Themes” section to automatically build a child using your currently active theme.This is fantastic if you don’t want to mess with FTP and are looking to play around with some new ideas.You can also use Child Themify plugin for creating the child themes.

 

If you plan to edit these files within the admin panel you’ll also enjoy clearer syntax highlighting for that you can install the Advanced Code Editor for some much-improved functionality. This makes wading through PHP code blocks and HTML/CSS a whole lot more manageable.

 

Additional Resources & references

 

1. http://wp.tutsplus.com/tutorials/theme-development/child-themes-basics-and-creating-child-themes-in-wordpress/

2. http://www.hongkiat.com/blog/wordpress-child-themes-dev/

 

Hope this all helps.