PHP Arrays
PHP Arrays
You can create an array with the array function, or use the
explode function (this is very useful when reading files
into web programs…)
$my_array = array(1, 2, 3, 4, 5);
$pizza = "piece1 piece2 piece3
piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
$highs = array("Mon" => 74, "Tue" => 70, "Wed" => 67,"Thu" =>
62, "Fri" => 65);
if (array_key_exists("Tue", $highs))
{$tues_high = $highs["Tue"];
print "The high on Tuesday was $tues_high <br />“;}
else print "There is data for Tuesday in the \$highs array <br />";
$list = array("Bob", "Fred", "Alan", "Bozo");
$len = sizeof($list);
output :
The first city is Hoboken
list of all the elements of that array:
$city = current($cities);
print("$city <br />");
while ($city = next($cities))
print("$city <br />");
The loop iterations stop when the value of the current element is
FALSE
• The next function first moves the current pointer and then
returns the value being referenced by the current pointer.
The each function, which returns a two-element
array consisting of the key and the value of the
current element, avoids this problem
• The ksort function sorts its given array by keys, rather than
values. The key-value associations are maintained by the
process.
function
• function names are not case sensitive
• default parameter-passing mechanism of PHP is pass by
value
$name = trim($_POST['name']);
if(empty($name)) {
echo "Please enter your name"; exit;
}
echo "Success";
Validationn- ex2
if(empty($_POST['selectedcake']))
{ $select_cake_error = "Please select a cake
size";
$error=true;
} else
{ $selected_cake = $_POST['selectedcake']; }
file_exists
<?php $file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Attempt to open the file
$handle = fopen($file, "r"); }
else
{ echo "ERROR: File does not exist."; }
?>
Files in PHP
• fread
• file
• file_get_contents
• fgets
• fgetc
• ----------------
• fwrite
• file_put_contents
file
<?php $file = "data.txt"; // Check the
existence of file
if(file_exists($file))
{ // Reads and outputs the entire file
file($file) or die("ERROR: Cannot open
the file."); }
else
{ echo "ERROR: File does not exist."; }
?>
file_get_contents
<?php $file = "data.txt";
// Check the existence of file
if(file_exists($file)){
// Reading the entire file into a string
$content = file_get_contents($file) or
die("ERROR: Cannot open the file.");
// Display the file content
echo $content; }
else{ echo "ERROR: File does not exist.";
} ?>
file_put_contents
<?php $file = "note.txt";
// String of data to be written $data =
"The quick brown fox jumps over the
lazy dog.";
// Write data to the file
file_put_contents($file, $data) or
die("ERROR: Cannot write the file.");
echo "Data written to the file
successfully."; ?>