0% found this document useful (0 votes)
1K views

PHP Notes: Arrays

The document provides an overview of PHP arrays, including defining arrays, accessing array values by index, nesting arrays, changing array values, and using keys to reference array values. It also summarizes common array functions like count, max, min, sort, and functions to convert arrays to strings and vice versa. Additional sections cover loops, pointers, functions, includes, debugging, and links.

Uploaded by

pasanbsb
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

PHP Notes: Arrays

The document provides an overview of PHP arrays, including defining arrays, accessing array values by index, nesting arrays, changing array values, and using keys to reference array values. It also summarizes common array functions like count, max, min, sort, and functions to convert arrays to strings and vice versa. Additional sections cover loops, pointers, functions, includes, debugging, and links.

Uploaded by

pasanbsb
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

PHP Notes

Arrays

<? /*
Think of an array like an expandable file folder where you can put items in
each of the pockets
There are no limits to how many pockets it can have (not that you'll need to
worry about at least)
Then you can reference those items by the pocket number (or "index")
(This is the "value" of that "position" in the array)
Be careful! Pockets are numbered starting at 0 (0,1,2,3...) so the index of
the 2nd pocket is 1
*/?>

<?php
// defining a simple array
$array1 = array(4,8,15,16,23,42);

// referencing an array value by its index


echo $array1[0];

// arrays can contain a mix of strings, numbers, even other arrays


$array2 = array(6,"fox", "dog", array("x", "y", "z"));

// referencing an array value that is inside another array


echo $array2[3][1];
?>

<?php
// Changing values in an array that has already been defined
// It's just like variables but you use the index to reference the array
position

$array2[3] = "cat";

echo $array2[3];
?>

<?php

// You can also assign labels to each pocket (called "keys"),

$array3 = array("first_name" => "Kevin", "last_name" => "Skoglund");


// which will allow you to use the key to reference the value in that array
position.

echo $array3["first_name"] . " " . $array3["last_name"] . "<br />";

$array3["first_name"] = "Larry";

echo $array3["first_name"] . " " . $array3["last_name"] . "<br />";

?>

<br />

A good way to see the values inside an array during development:<br />

<pre><?php print_r($array2); ?></pre>

Array Functions

<?php $array1 = array(4,8,15,16,23,42); ?>

Count: <?php echo count($array1); ?><br />


Max value: <?php echo max($array1); ?><br />
Min value: <?php echo min($array1); ?><br />
<br />
Sort: <?php sort($array1); print_r($array1); ?><br />
Reverse Sort: <?php rsort($array1); print_r($array1); ?><br />
<br />
<?php

// Implode converts an array into a string using a "join string"

// Explode converts a string into an array using a "divide string"

?>
Implode: <?php echo $string1 = implode(" * ", $array1); ?><br />
Explode: <?php print_r(explode(" * ", $string1)); ?><br />
<br />
In array: <?php echo in_array(15, $array1); // returns T/F ?
><br />
Constants

define("MAX_WIDTH", 980);

Floating Points

Floating point: <?php echo $myFloat = 3.14; ?><br />


Round: <?php echo round($myFloat, 1); ?><br />
Ceiling: <?php echo ceil($myFloat); ?><br />
Floor: <?php echo floor($myFloat); ?><br />

Logical functions

<?php

// ! is a logical NOT and it negates an expression


unset($a);

if (!isset($a)) { // read this as "if not isset $a" or "if $a is not set"
$a = 100;
}
echo $a;

?>

<?php

// Use a logical test to determine if a type should be set


if (is_int($a)) {
settype($a, "string");
}
echo gettype($a);
?>

String Functions

Lowercase: <?php echo strtolower($thirdString); ?><br />


Uppercase: <?php echo strtoupper($thirdString); ?><br />
Uppercase first-letter: <?php echo ucfirst($thirdString); ?><br />
Uppercase words: <?php echo ucwords($thirdString); ?><br />
<br />
Length: <?php echo strlen($thirdString); ?><br />
Trim: <?php echo $fourthString = $firstString .
trim($secondString); ?><br />
Find: <?php echo strstr($thirdString, "brown"); ?><br />
Replace by string: <?php echo str_replace("quick", "super-fast",
$thirdString); ?><br />

Type casting

<?php

// gettype will retrieve an item's type


echo gettype($var1); echo "<br />";
echo gettype($var2); echo "<br />";

// settype will convert an item to a specific type


settype($var2, "string");
echo gettype($var2); echo "<br />";

// Or you can specify the new type in parentheses in front of the item

$var3 = (int) $var1;


echo gettype($var3); echo "<br />";

?>

<?php // You can also perform tests on the type (which return booleans) ?>
is_array: <?php echo is_array($var1); // result: false ?
><br />
is_bool: <?php echo is_bool($var1); // result: false ?
><br />
is_float: <?php echo is_float($var1); // result: false ?
><br />
is_int: <?php echo is_int($var1); // result: false ?
><br />
is_null: <?php echo is_null($var1); // result: false ?
><br />
is_numeric: <?php echo is_numeric($var1); // result: false ?
><br />
is_string: <?php echo is_string($var1); // result: true ?
><br />

For each loops

<?php /* foreach loops

foreach (array_expression as $value)


statement;

foreach (array_expression as $key => $value)


statement;

Works only on arrays!


*/ ?>

<?php
$ages = array(4, 8, 15, 16, 23, 42);

?>

<?php
// using each value
foreach($ages as $age) {
echo $age . ", ";
}

?>

<?php
// using each key => value pair
foreach($ages as $position => $age) {
echo $position . ": " . $age . "<br />";
}

?>
<br />
<?php
// Just for fun...
$prices = array("Brand New Computer"=>2000,
"1 month in Lynda.com Training Library"=>25,
"Learning PHP" => "priceless");
foreach($prices as $key => $value) {
if (is_int($value)) {
echo $key . ": $" . $value . "<br />";
} else {
echo $key . ": " . $value . "<br />";
}
}
?>

Pointers

<?php // Pointers and while loops revisited

$ages = array(4, 8, 15, 16, 23, 42);


?>

<?php
// Arrays have pointers that point to a position in the array
// We can use current, next and reset to manipulate the pointer
echo "1: " . current($ages) . "<br />";
next($ages);
echo "2: " . current($ages) . "<br />";
reset($ages);
echo "3: " . current($ages) . "<br />";

?>

<?php

// while loop that moves the array pointer

// It is important to understand this type of loop before working with


databases

while ($age = current($ages)) {


echo $age . ", ";
next($ages);
}
?>

Functions - Global variables and default values

<?php /* global variables in functions

Variables inside a function aren't the same as the variable outside it

Declaring a variable as global "pulls in" the variable

as it exists outside the function so that the function can use it.

*/

// Example using a global variable


$bar = "outside";
function foo() {
global $bar;
$bar = "inside";
}
foo();

// guess which this will return before you try it


echo $bar . "<br />";

?>
<br />
<?php

// Example using a local variable, arguments and return values


$bar = "outside";
function foo2($var) {
$var = "inside";
return $var;
}
$bar = foo2($bar);
echo $bar . "<br />";

// use sparingly for variables which truly are global & need to be accessed
many times from many places
// don't declare globals out of laziness--pass in arguments and return values
instead
?>
<br />

<?php /* default argument values

Default values are a very good habit to have

Not only does it make your function flexible and error-resistant

but it also helps remind you want type of value you expect to be input

Arguments with defaults should to the right of any required arguments

*/

function paint($color="red", $room="office") {


echo "The color of the {$room} is {$color}.";
}
paint("blue","bedroom");
?>

Includes

<?php

// inserts the contents of the file "included_func.php" as if

// those same lines had been typed here.

include("included_func.php");

?>

<?php hello("Everyone"); ?>

<?php
/* In addition to include(), you can also use:
include_once();
require();
require_once();

include_once and require_once will include a file UNLESS it


has already been included (PHP keeps track).
Useful for files with constants & functions because
they can't be defined more than once.
*/

?>

Debugging

echo $variable
print_r($array) - readable array information
gettype($variable) - variable type
var_dump($variable) - type and value
get_defined_vars() - array of defined variables

Links

<?php

// A string with lots of characters that aren't HTML friendly


$linktext = "<Click> & you'll see";

?>

<a href="secondpage.php?name=

<?php echo urlencode("kevin skoglund"); ?>&id=42">

<?php echo htmlspecialchars($linktext); ?>

<?php
// view values in $_GET array
print_r($_GET);
// assign $_GET array values to variables for easier use
$id = $_GET['id'];
$name = $_GET['name'];
echo "<br /><strong>" . $id . ": {$name}</strong>";
?>

<?php
// illustrating the difference between urlencode and rawurlencode
$string = "kevin skoglund";
echo urlencode($string);
echo "<br />";
echo rawurlencode($string);

?>

URL encoding

<?php

/* For clarity, I'm defining each part of a link at the top

then showing how to "clean" them using three different functions

so that they are suitable for use on a web page.

*/

$url_page = 'php/created/page/url.php'; // <- page the link will request

$param1 = 'this is a string'; // <- parameter to be sent in the URL string

$param2 = '"bad"/<>character$'; // <- another parameter, with HTML unfriendly


characters

$linktext = "<Click> & you'll see"; // <- text of the link, with HTML
unfriendly characters

?>
<?php
// this gives you a clean link to use
$url = "http://localhost/";
$url .= rawurlencode($url_page);
$url .= "?param1=" . urlencode($param1);
$url .= "&param2=" . urlencode($param2);

// htmlspecialchars escapes any html that


// might do bad things to your html page
?>
<a href="<?php echo htmlspecialchars($url); ?>">
<?php echo htmlspecialchars($linktext); ?>
</a>

<?php
/*
Summary:
- Use rawurlencode for parts that come before "?".
- Use urlencode for all GET parameters (values that come
after each "=").
(POST parameters are automatically encoded)
- Use htmlspecialchars for HTML tag parameters and HTML text
content.
*/
?>

Forms

page1.php

<form action="process.php" method="post">


Username: <input type="text" name="username" value="" />
<br />
Password: <input type="password" name="password" value="" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

process.php

<?php
// Ultra-simple form processing
// Just retrieve the value and return it to the browser

$username = $_POST['username'];
$password = $_POST['password'];

echo "{$username}: {$password}";


?>

Cookies

<?php // Setting a cookie

// setcookie(name, value, expiration);


setcookie('test', 45, time()+(60*60*24*7));
?>

<?php // Reading the value of a cookie

// give $var1 a default value


$var1 = 0;
// if cookie with name 'test' exists then set $var1 to its value
if (isset($_COOKIE['test'])) {
$var1 = $_COOKIE['test'];
}
echo $var1;
?>

<?php // Deleting a cookie

// set cookie value to 0 and expiration to the distant past


setcookie('test', 0, time()-(60*60*24*7)); ?>
Sessions

<?php
session_start();
/* session_start() MUST be called before creating, accessing or
deleting a session
session_start() MUST be called before any white space or HTML is
output
to the browser (unless output buffering has been turned on).
Says to PHP: get the session cookie from the browser and open up
that file for use
or if no session cookie was found, or no file that matches,
create a new one
*/
?>

<html>
<head>
<title>Sessions</title>
</head>
<body>

<?php
// since a session has been started above, it's available and ready for use

// set values in the session


$_SESSION['first_name'] = "kevin";
$_SESSION['last_name'] = "skoglund";
?>

<?php

// read values from the session

$name = $_SESSION['first_name'] . " " . $_SESSION['last_name'];

echo $name;

?>
</body>
</html>

Headers

<?php

// This is how you redirect a page (aka "302 redirect")

header("Location: basic.html");

exit;

// Always use exit to keep anything else from the page from executing

/* header() must come before any whitespace or HTML is output

to the browser unless output buffering is turned on.

Only 1 header can be sent; if HTML has been sent, then the header already went
too.
*/
?>
<?php
// This is how you return a 404 error (or another response code)
// header("HTTP/1.0 404 Not Found");
// exit;
?>
<html>
<head>
<title>Headers</title>
</head>
<body>

</body>
</html>

// See related links for more status codes

// Use this header instruction to fix 404 headers


// produced by url rewriting...
header('HTTP/1.1 200 OK');

// Page was not found:


header('HTTP/1.1 404 Not Found');

// Access forbidden:
header('HTTP/1.1 403 Forbidden');

// The page moved permanently should be used for


// all redrictions, because search engines know
// what's going on and can easily update their urls.
header('HTTP/1.1 301 Moved Permanently');

// Server error
header('HTTP/1.1 500 Internal Server Error');

// Redirect to a new location:


header('Location: http://www.example.org/');

// Redriect with a delay:


header('Refresh: 10; url=http://www.example.org/');
print 'You will be redirected in 10 seconds';

// you can also use the HTML syntax:


// <meta http-equiv="refresh" content="10;http://www.example.org/ />

// override X-Powered-By value


header('X-Powered-By: PHP/4.4.0');
header('X-Powered-By: Brain/0.6b');
// content language (en = English)
header('Content-language: en');

// last modified (good for caching)


$time = time() - 60; // or filemtime($fn), etc
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT');

// header for telling the browser that the content


// did not get changed
header('HTTP/1.1 304 Not Modified');

// set content length (good for caching):


header('Content-Length: 1234');

// Headers for an download:


header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
// load the file to send:
readfile('example.zip');

// Disable caching of the current document:


header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Pragma: no-cache');

// set content type:


header('Content-Type: text/html; charset=iso-8859-1');
header('Content-Type: text/html; charset=utf-8');
header('Content-Type: text/plain'); // plain text file
header('Content-Type: image/jpeg'); // JPG picture
header('Content-Type: application/zip'); // ZIP file
header('Content-Type: application/pdf'); // PDF file
header('Content-Type: audio/mpeg'); // Audio MPEG (MP3,...) file
header('Content-Type: application/x-shockwave-flash'); // Flash animation

// show sign in box


header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
print 'Text that will be displayed if the user hits cancel or ';
print 'enters wrong login data';
Databases

<?php

// Five steps to PHP database connections:

// 1. Create a database connection

// (Use your own servername, username and password if they are


different.)

// $connection allows us to keep refering to this connection after it


is established

$connection = mysql_connect("localhost","root","OtlPHP07");

if (!$connection) {
die("Database connection failed: " . mysql_error());

// 2. Select a database to use


$db_select = mysql_select_db("widget_corp",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}

?>
<html>
<head>
<title>Databases</title>
</head>
<body>
<?php

// 3. Perform database query


$result = mysql_query("SELECT * FROM subjects", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}

// 4. Use returned data


while ($row = mysql_fetch_array($result)) {
echo $row["menu_name"]." ".$row["position"]."<br />";
}

?>
</body>
</html>
<?php

// 5. Close connection
mysql_close($connection);
?>

You might also like