PHP Interview Questions - Set 5

PHP Interview Questions

This page contains PHP interview questions and answers.

Q1: Convert the following string into an array of words using PHP code

The string: The quick brown fox jumps over the lazy dog.

Answer:

We can use the explode function to convert the string to an array of words.

$str = "The quick brown fox jumps over the lazy dog";
$arr = explode(" ", $str);

Q2: Convert the following JSON string into an array using PHP code

JSON string: { "name": "Yusuf Shakeel", "points": 10 }

Answer:

To covert a JSON string into an array we can use the json_decode() function.

$str = '{ "name": "Yusuf Shakeel", "points": 10 }';
$arr = json_decode($str, true);

Q3: Convert the following array into a string separated by pipe symbol in PHP code

Array: [ "Hello", "World" ]

Answer:

We can use the implode() function to covert the array into a string.

$arr = [ "Hello", "World" ];
$str = implode("|", $arr);

Q4: How will you stop the execution of a PHP script?

We can use the exit() function to stop the execution of a PHP script.

Q5: Write "Hello World" text inside a file using PHP code

To write text inside a file we have to take help of the fopen(), fwrite() and fclose().

// create a new file in write mode
$handle = fopen("hello.txt", "w");

// write the text
fwrite($handle, "Hello World");

// close
fclose($handle);

Q6: How are session and cookie different?

A session is saved on the server side whereas a cookie is saved on the client side.

A cookie may live for a longer period of time even if the user closes the browser but a session ends as soon as the user closes the browser.

Session can store multiple variable whereas cookie have limited storage and can't store too much of data.

Q7: How will you start and stop a session in PHP?

To start a session we take help of the session_start() function and we use the session_destroy() function to stop/destory session.

Q8: How will you access session value in PHP?

We access value stored in session using the $_SESSION associative array.

Q9: How will you access cookie data in PHP?

To access cookie data in PHP we use the $_COOKIE associative array.

Q10: How will you set cookie in PHP?

We use the setcookie function to set cookie in PHP.

In the following example we are setting cookie for a website.

Name of the cookie is mycookie and the value stored is Hello World.

The expiry time is set to 3600 seconds from the moment the cookie is created so, we are using time() + 3600.

We want the cookie to be accessible throughout the domain so, the path is set to /.

And we want to transmit cookie only in secure channel so we are setting secure to true.

setcookie('mycookie', 'Hello World', time()+3600, '/', true);