PHP Interview Questions
This page contains PHP interview questions and answers.
The string: The quick brown fox jumps over the lazy dog
.
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);
JSON string: { "name": "Yusuf Shakeel", "points": 10 }
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);
Array: [ "Hello", "World" ]
We can use the implode()
function to covert the array into a string.
$arr = [ "Hello", "World" ];
$str = implode("|", $arr);
We can use the exit()
function to stop the execution of a PHP script.
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);
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.
To start a session we take help of the session_start()
function and we use the session_destroy()
function to stop/destory session.
We access value stored in session using the $_SESSION
associative array.
To access cookie data in PHP we use the $_COOKIE
associative array.
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);
ADVERTISEMENT