session_status() function
if (session_status() == PHP_SESSION_NONE) { session_start(); } if (session_status() == PHP_SESSION_ACTIVE) { echo "Session is started."; } else { echo "Session is not started."; }
Free PHP Code Examples
session_status() function
if (session_status() == PHP_SESSION_NONE) { session_start(); } if (session_status() == PHP_SESSION_ACTIVE) { echo "Session is started."; } else { echo "Session is not started."; }
in_array() function
$array = array('apple', 'banana', 'orange', 'pear'); $value = 'banana'; if (in_array($value, $array)) { echo "$value is in the array."; } else { echo "$value is not in the array."; }
file_exists() function
$filename = 'example.txt'; if (file_exists($filename)) { echo "The file $filename exists."; } else { echo "The file $filename does not exist."; }
isset() function
if (isset($variable)) { echo "The variable exists."; } else { echo "The variable does not exist."; }
empty() function
$str = ''; if (empty($str)) { echo "The string is empty"; } else { echo "The string is not empty"; }
Direct comparison
$str = ''; if ($str === '') { echo "The string is empty"; } else { echo "The string is not empty"; }
array_key_exists() function
$array = array( "key1" => "value1", "key2" => "value2", "key3" => "value3" ); $keyToCheck = "key2"; if (array_key_exists($keyToCheck, $array)) { echo "The key '$keyToCheck' exists in the array."; } else { echo "The key '$keyToCheck' does not exist in the array."; }
empty() function
$arr = array(); if (empty($arr)) { echo "The array is empty"; } else { echo "The array is not empty"; }
count() function
$arr = array(); if (count($arr) == 0) { echo "The array is empty"; } else { echo "The array is not empty"; }
sizeof() function
$arr = array(); if (sizeof($arr) == 0) { echo "The array is empty"; } else { echo "The array is not empty"; }
Method 1
<?php $name = "John"; $string = "Hello, " . $name . "!"; echo $string; ?>
Method 2
<?php $name = "John"; $string = "Hello, $name!"; echo $string; ?>
$array[] = $value
<?php $array = array(); $array[] = "element1"; $array[] = "element2"; $array[] = "element3"; print_r($array); ?>
array_push()
<?php $array = array(); array_push($array, "element1"); array_push($array, "element2"); array_push($array, "element3"); print_r($array); ?>
MySQLi
<?php $servername = "localhost"; $username = "username"; $password = "password"; $database = "database_name"; $conn = new mysqli($servername, $username, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>
PDO
<?php $servername = "localhost"; $username = "username"; $password = "password"; $database = "database_name"; try { $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>