Browse By

Array, Session and Cookies in PHP

Spread the love

Array in PHP

It is an special type of variable which can store multiple values in single variable.

eg:

<?php
$bikes = array("Pulsar", "Hero Honda", "Discover");
$arrlength = count($bikes);

for($x = 0; $x < $arrlength; $x++) {
    echo $bikes[$x];
    echo "<br>";
}
?>
here count() is used to count the total value in array $bikes and $bikes[] is used to print value using index like $bikes[0] is the first element of array $bikes.

Associative array and its loop

<?php
$age = array("manoj"=>"32", "suraj"=>"27", "ram"=>"37");
foreach($age as $x => $x_value) {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
}
?>
Array creating using key and value pair is called associative array.

What is session and how to use it in php?

session is basically a bit of information which is used across multiple pages and its is executed at server side.

if you create any login system you need to create session to track users and its working thorough out the application.

<?php
session_start();  // this code is to start session
session_destroy();  // This code will destroy all the session of current application 
unset($_SESSION['session_name']); // if you want to delete session one by one you need to use this code.
?>

how to use session?

<?php
session_start();
$_SESSION['session_name'] = "information you want to store as a session."; // This is how you store information into session.
echo $_SESSION['session_name']; // to print session.
unset($_SESSION['session_name']); // to delete this session
print_r($_SESSION); // to print all the available session live.
?>
The above code are all about session. in the next tutorial you will get to know about session in details.

What is cookies and how to use it in PHP?

cookies are similar to session as it is also used to store bit if information which can be used across multiple pages. On of the most important fact is cookies are client side and store on local system and we can provide time to auto dispose/expire of cookies which we can not do in session.

<?php
$cookie_name = "user_cookies";
$cookie_value = "manoj karn blog";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
echo $_COOKIE[$cookie_name];   // Print cookies value.
setcookie("user", "", time() - 3600);  // to delete cookies
?>

Leave a Reply

Your email address will not be published. Required fields are marked *