Archive for the ‘PHP’ Category

Basic Questions on PHP Part2

November 16, 2009 2 comments
After getting a very good response on my earlier compilation “Basic Questions on PHP “, I am back with a new compilation of basic PHP questions on arrays.
1- How to check if a value exists in an array?
Ans Use in_array() function for this.
$sample = array(“banana”,”apple”,”pear”,”banana”);
$newvalue = “pear”;
if (in_array($newvalue,$sample)) { echo “$newvalue is already in the array!”; }
2- How to create an array of consecutive numbers and array of alphabets?
$arr_of_numbers = range(1,10);//$arr_of_numbers = array(1,2,3,4,5,6,7,8,9,10)
$arr_of_letters = range(a,m); //$arr_of_letters = array(a,b,c,d,e,f,g,h,i,j,k,l,m)
3- How to reset an array?
Ans: The reset() function does this and returns the first element of the array.
$sample = array(‘itm1′,’itm2′,’itm3′,’itm4’);
$first = reset($sample);
echo $first; //itm1
4- How to count the frequency a value appears in an array?
Ans: array_count_values() function does this operation. It returns an associative array with values as keys and their fequencies as values.
$sample_arr = array(1,0,1,2,0,2,2,2,3,4,2,5,2,3,5,3,1,5);
$most_popular = array_count_values($sample_arr);
output: Array(
[1] => 3
[0] => 2
[2] => 6
[3] => 3
[4] => 1
[5] => 3
5- How to remove last element of an array?
Ans: array_pop() function does this.
$sample = array(“One”,”Two”,”Three”,”Four”,”Five”,”Six”);
$last = array_pop($sample);
echo “last element is “.$last; //last element is Six…
6- How to sort an array with alphanumeric values?
Ans: natsort() function will do this.
$sample = array(“1.gif”,”2.png”,”20.jpg”,”10.gif”);
Array (
[0] => 1.gif
[1] => 2.png
[3] => 10.gif
[2] => 20.jpg
7- How to change an array into string?
Ans: We can achieve this using “implode()” function.
$sample = array(“I”,”love”,”PHP”);
$sample_to_string = implode(” “, $sample);
echo “$sample_to_string”;//I love PHP
8- How to remove duplicate values from an array?
Ans: The array_unique() function will do this.
$sample = array(“pear”,”apple”,”pear”,”banana”);
$sample_to_unique = array_unique($sample);
[0] => pear
[1] => apple
[2] => banana
9- How to interchange key to values and visa versa of an array?
Ans: We can do this using array_flip() function.
$sample = array(“John”,”Alice”,”Boby”);
$flipped = array_flip($sample);
[0] => John
[1] => Alice
[2] => Boby
[John] => 0
[Alice] => 1
[Boby] => 2
10- How to add an element at the begining of an array?
Ans: The array_unshift() does this. This function returns the number of elements in the array after additions of the new element.
$sample = array(2,3,4,5,6);
$no_sample = array_unshift($sample,1);
echo “Number of elements: $no_sample \n\n”;
Number of elements: 10
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
Hope these questions will help the PHP folks. I will come soon with some new PHP stuff.
Categories: PHP Tags: , ,

PHP-Showing image having name with “%2F”

June 26, 2008 Leave a comment

If you want to display an image on an HTML page, you can simply use the <img> tag. But if the image name consists of the html entity “%2F”, it is difficult to do that. For example:

The image name is : foo%2Fbar.png

<img src=”/images/foo%2Fbar.png” title=”image” alt=”image” />

The html page will try to get the image from the directory: /images/foo/bar.png

This way the page will never get the image and won’t be able to display that. I have a trick to solve this problem. Here it is:



<p>The correct image is:

<img src=”<?php echo substr_replace(“/images/foo%2Fbar.png”, ‘%252F’, -10, -7) ?>” alt=”image” title=”image” />



This code will display the image by replacing “%2F” with “%252F” and you will not be blamed to have extra subdirectories.

Categories: PHP Tags:

Have some Cookies!!

August 21, 2006 Leave a comment

Q: What are cookies?

Ans: A Cookie is a small amount of data stored on the client’s browser in compliance with a request from a server or script. The information is constantly passed in HTTP headers between the browser and web server; the browser sends the current cookie as part of its request to the server and the server sends updates to the data back to the user as part of its response. Once a cookie is created, it will expire after a specified time period.

Q: What is the need of cookies?

Ans: HTTP is a stateless protocol. Therefore, every-page a user downloads from your server represents a separate connection.

1-Cookies allow you to do neat things, like automatically log a user into your site when he loads a page in his browser, or store temporary information about your user, such as what items he has in a shopping cart.

2- Allows a user to remain ‘logged on’ until he explicitly logs out or the browser window is closed.

3- After a cookie is set, only the originating host can read the data, ensuring that the user’s privacy is respected.

Q: How we can set a cookie?

Anw: You can set a cookie in a PHP script in two ways:

Using header() function:

header(“SET-COOKIE: newcookie=mycookie; expires=Sat, 26-Aug-06 14:40:28 GMT; path=/;”);

Using setcookie() function:

setcookie(name, value, expiration, path, domain, secure, httponly);



setcookie(“newcookie”, “mycookie”, time()+3600, “/”,””, 0);



<head><title>Setting a new cookie</title></head>


<?php if(isset($_COOKIE[‘newcookie’])) {

echo “<p> Hello again, your chosen cookie is “;

echo “{$_COOKIE[‘newcookie’]} </p>”;

} else {

echo “<p> Hello you. This may be your first visit</p>”;

} ?>



Q: How to access the already set cookie?

Ans: With the help of the superglobal variable $_COOKIE[‘cookie_name’]

Q: How to determine the expiration of the cookie?

Ans: The “expiration” variable in the setcookie() function decides the expiration of the cookie. Here are some amount of time which signify the determination of the expiration time/date of a cookie

One Minute: 60
Ten Minutes: 600
Half-an-Hour: 1800
One Hour: 3600
One Day: 86400
One Week: 604800
Two Weeks: 1209600
One Month (30 days): 2592000
One Year (365 days): 31536000

Q: How to delete a cookie?

Ans: There are two ways to reset/destroy a cookie:

Reset a cookie by specifying already expired time:-

setcookie(“newcookie”, “”, time()-60, “/”, “”, 0);
Reset a cookie by specifying its name only:-


Q: How we can create the session cookie?

Ans: To create a cookie that lasts only as long as the user is running the browser, pass setcookie() an expiry argument of 0.

setcookie(“session_id”, “8832”,0);

The browser does not remember this cookie after it has been quit or restarted.

Categories: PHP

Carriage return output!

July 7, 2006 4 comments

Q:- How can I produce carriage return delimited output of any file to the client side?
Ans:- One way to do it is to create the CSV file of the file or data and redirect it to client side. CSV file is Comma Separated Value, often used to exchange data between disparate applications. After downloading the file, it will automatically give the choices in which he wants to separate the data, and after selecting the option it will create the excel file.

Q:- So how one can create and redirect the CSV file to client?
Ans:- The following code will do that:
$content = (First create the file content/data, that may be through other function call)
header(“Pragma: cache”);
header(“Content-type: application/octet-stream”);
header(“Content-Disposition: attachment; filename=<filename>.csv”);
header(“Content-transfer-encoding: binary”);
header( “Last-Modified: ” . gmdate(“D, d M Y H:i:s”) . ” GMT” );
header( “Cache-Control: post-check=0, pre-check=0”, false );
header(“Content-Length: “.strlen($content));
print $content;

In this code I am talking only about to create the CSV file and redirect that to client. This is considered that the file content/data is already created.

Categories: PHP

Questions on Bitwise Operators in PHP

June 26, 2006 2 comments

Q:- What do you mean by bitwise operators?
Ans: The bitwise operators act on the binary representation on their operands. Each operand is first turned into a binary representation of the value before operation.

Q:- Do these operators work only on numbers?
Ans: No, they work for numbers as well as strings but they vary in their treatment of string operands of different lengths.

Q:- What is bitwise negation(~)?
Ans: It changes 1s to 0s and 0s to 1s in the binary representations of the operands. For string operands, the resulting value is a string of same length, with each character in the string negated. Read more…

Categories: PHP

Interview Questions on PHP

June 22, 2006 16 comments

Hey, I am back with some more questions on PHP. Enjoy!!

Q:- What is the difference between “GET” and “POST” methods?

Ans. Get and Post are methods used to send data to the server with the submission of the form. The default method is GET.

* The browser appends the data onto the url when GET method is used, while the data is sent as standard input when POST method is used.
* When the processing of the form has no side effects, means just for getting(retrieving) data, the GET method should be used and POST method should be used when the form processing has side effects(for example, modification of a database or subscription to a service).

Example: Suppose Sachin is filling up a form with the following information:

Name: Sachin Tendulkar



If the form uses GET method then the location box will show the string after submitting the form like this: &Age=35&Sex=Male&Choice=Cricket
and if POST is used, then the location box will show:

Q:- What is the difference between echo and print?

Ans. Both are the constructs to print the string on the screen. echo just outputs the contents to the screen following the construct while print returns TRUE on successful output and FALSE if it was unable to print out the string. echo can take multiple parameters while print cannot. Also echo is faster than print in execution.

Q:- What is the difference include() and require()?
Ans. Both the functions are used to include and evaluate the specific file, but the only difference is require() produces FATAL ERROR and stops the execution if the specified file is not found while include() produces a warning message only and proceeds the execution.

Q:- What is meant by nl2br()?

Ans. This function inserts HTML line breaks before all newlines in a string

example: <?php
echo nl2br(“I am not getting\n what you are saying”);
Output: I am not getting<br />
what you are saying

Q:- What is the differen between strstr() and stristr() functions?

Ans. strstr() function is used to return the sub string from first occurrence of string point from the string base.If string point is not found, returns FALSE. syntax: strstr(string base,string point)
examle: <?php
$email = ‘’;
$domain = strstr($email, ‘@’);
echo $domain;
stristr() does the same thing in Case-insensitive manner.

Who will come with smart comments? Let’s see.

Categories: PHP

Who would like to be the first!!

June 14, 2006 1 comment

Just wondering!! While writing for the new post, suddenly clicked that after every post, the bottom line says “Smart suggestions are always welcome”, how the blog sites provide this facility. Means how anyone can add comments, can’t edit the posts, rate the post etc. I want to know at coding level. I am digging for the solution. Who would like to be the first to provide me the “digging tool”? That can be anything, site references, code pieces, blog references.

Soon you will get my new post regarding this. Lets make a race.

Categories: PHP