PHP Notes: Arrays
PHP Notes: Arrays
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);
<?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
$array3["first_name"] = "Larry";
?>
<br />
A good way to see the values inside an array during development:<br />
Array Functions
?>
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
Logical functions
<?php
if (!isset($a)) { // read this as "if not isset $a" or "if $a is not set"
$a = 100;
}
echo $a;
?>
<?php
String Functions
Type casting
<?php
// Or you can specify the new type in parentheses in front of the item
?>
<?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 />
<?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
// 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
as it exists outside the function so that the function can use it.
*/
?>
<br />
<?php
// 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 />
but it also helps remind you want type of value you expect to be input
*/
Includes
<?php
include("included_func.php");
?>
<?php
/* In addition to include(), you can also use:
include_once();
require();
require_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 href="secondpage.php?name=
<?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
*/
$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 .= "¶m2=" . urlencode($param2);
<?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
process.php
<?php
// Ultra-simple form processing
// Just retrieve the value and return it to the browser
$username = $_POST['username'];
$password = $_POST['password'];
Cookies
<?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
<?php
echo $name;
?>
</body>
</html>
Headers
<?php
header("Location: basic.html");
exit;
// Always use exit to keep anything else from the page from executing
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>
// Access forbidden:
header('HTTP/1.1 403 Forbidden');
// Server error
header('HTTP/1.1 500 Internal Server Error');
<?php
$connection = mysql_connect("localhost","root","OtlPHP07");
if (!$connection) {
die("Database connection failed: " . mysql_error());
?>
<html>
<head>
<title>Databases</title>
</head>
<body>
<?php
?>
</body>
</html>
<?php
// 5. Close connection
mysql_close($connection);
?>