Tuesday, December 21, 2010

PHP Variable Reference

Variables in PHP may be passed by reference. If a variable is passed by reference, the function it is being passed to can modify the variable. A variable reference is not the same as a pointer, they are symbol table aliases. When a variable is passed by reference, the reference sign,"&" is only a part of the function definition. A variable may be passed to a function as follows:
double ($value1);
The function:
function double (&$invalue)
{
$invalue += $invalue;
}

PHP Array Functions

  • array() - Used to create an array
  • asort()
  • arsort()
  • count() - Counts the number of array items.
  • each()
  • ksort()
  • list() - Used to create an array
  • next() - Get the next array element
  • prev() - Get the previous array element
  • rsort()
  • sort()
  • uasort()
  • usort()
  • uksort()

Array_multisort Function

This function is used to sort multiple array entries. The example below reads a database then uses a search string called $searchvalue to search through entries in the database for matches. It uses the substr_count() function to count the number of matches. It uses the array_multisort() function to sort the results.
array_multisort($matchscore, $desc, $id, $url);
This example does not explain the use of the mysql database functions in detail, they are explained in more detail in later sections. The lines are also numbered for reference.
1.  $query1="select * from " . $mainsection;  //select all entries in the database
2. $result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1);
3. $nomatches=0;
4. while($thisrow=mysql_fetch_row($result)) //get one row which is each entry for the section
5. {
6. $matches=0;
7. $urlmatches=substr_count(strtolower($thisrow[1]),$searchvalue); //url - 140
8. $titlematches=substr_count(strtolower($thisrow[2]),$searchvalue); //title
9. $descmatches=substr_count(strtolower($thisrow[3]),$searchvalue); //decription
10. $matches=$urlmatches*3 + $titlematches*5 + $descmatches;
11. $matchscore[$nomatches]=$matches; //record the number of matches for each row in an array
12. $url[$nomatches]=$thisrow[1];
13. $title[$nomatches]=$thisrow[$2];
14. $id[$nomatches]=$thisrow[0];
15. $desc[$nomatches]=$thisrow[3];
16. $nomatches++;
17. } //end while
18. array_multisort($matchscore, $desc, $id, $url);
19. for ($i5=$nomatches-1; $i5>=0; $i5--) //get one row which is each entry for the section
20. {
21. if ($matchscore[$i5] > 0)
22. {
23. echo "<table width=\"100%\" cellspacing=0 border=0 cellpadding=0 align=\"center\">"; //266
24. echo "<tr><td width=\"90%\" bgcolor=\"#80b0ff\" bordercolor=\"#000080\" nowrap valign=\"top\">";
25. echo "<font size=\"2\">Match Rank=" . $matchscore[$i5] . " </font><a href=\"$url[$i5]\">" . $title[$i5] . " </a>";
26. echo "</td></tr>";
27. echo "<tr><td width=\"90%\" valign=\"top\">";
28. echo $desc[$i5] . "<br>"; //description
29. echo "<font face=\"Arial\" size=\"2\"><i>";
30. echo "</td></tr></table><br>";
31. } //end if $matchscoreɬ
32. }
Line 1 sets up the query for the database.
Line 2 reads the database.
Line 3 initializes the counter that tracks the number of matches.
Line 4 reads individual rows of the query results until all rows are read.
Lines 7-9 count the number of matches in each entry
Line 10 sets total match score which is weighed based on whether a match was found in the URL, title, and/or description.
Line 11 creates and places values in the array, $matchscore[], which is later used as a basis to sort the entries.
Lines 12-15 sets array values based on the match score and database entries.
Line 18 performs the sort of the array based on the matchscore first.
Line 19 sets up a loop to display the arrays in reverse order since the array was sorted from lowest to highest value.
Lines 22-31 display the matchstore, rl, url title, and description.

PHP Control Statements

if, elseif, else

if ( )
{
}
elseif ( )
{
}
else
{
}

switch

switch ( )
{
case condition1
break;
case condition2
break;
}

while

Syntax:
while (condition)
{
}

do

do
{
} while (condition)

for

Example use of the for statement:
<?php
for ( $n = 1; $n < 10; $n++)
{
echo "$n<BR>";
}
?>

foreach

Versions of PHP prior to version 4 do not support the foreach statement. The following code should list the contents of the array.
<?php
$tree = array("trunk", "branches", "leaves");
foreach ($tree as $part)
{
echo "Tree part: $part ";
}
?>

break

Is used to end the execution of a for, switch, or while statement

continue

This statement is used to skip the rest of the current loop.
<?php
for ( $n = 1; $n < 10; $n++)
{
echo "$n<BR>";
if ($n == 5) continue;
echo "This statement is skipped when $n = 5.<BR>";
}
?>
The continue statement can be given an optional parameter such as "continue 2" telling it how many levels of loops to skip.

PHP Example

The code listed below is an example showing how to embed PHP into an HTML file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Arachnophilia 3.9]">
<meta name="description" content="PHP Example">
<meta name="keywords" content="PHP example">
<title>PHP Example</title>
<link href="style.css" rel="stylesheet" type="text/css">
<head>
<body>

<h1 style="text-align: center">Example</h1>

<p>
<?
echo "This is a test!";
?>
</p>

</body>
</html>

PHP Execution Order

Server script programs such as Perl will run then the entire output is produced and sent to the client web browser. PHP does not execute like this. PHP executes from the top to the bottom of the page and can be mixed with HTML. This is especially important to be aware of when trying to set cookies in PHP. The example below shows PHP code being run based on a query string. A query string is a string that is appended to a url as follows:
<a href="ctt.php?firstselection">First Selection</a>
The query string that the program will receive in this example is "firstselection", and it is stored automatically in the PHP variable $QUERY_STRING. This example will not show the HTML header. PHP code is shown in blue, and HTML is shown in green.
<?php
if ($QUERY_STRING=="firstselection")
{
?>
<h1>First Selection Was Made</h1>
<?php
}
if ($QUERY_STRING=="secondselection")
{
?>
<h2>Second Selection Was Made</h2>
<?php
}
if ($QUERY_STRING=="thirdselection")
{
?>
<h3>Third Selection Was Made</h3>
<?php
}
else
{
?>
<p>no selection was made</p>
<?php
}
?>
In this example, if the string is "firstselection", a header of type 1 is used to display the selection. If the string is "secondselection", a header of type 2 is used to display the selection. If no selection or an unknown selection is made, a paragraph is displayed stating that "No selection was made".

PHP Objects

PHP supports the creation of classes and objects. A class can be created as follows:
class Auto {
var $position = 1;

function move ($distance)
{
$this->position += $distance;
}

function report()
{
echo "Position = " . (string) $this->position . "<BR>";
}
}
The object may be created as follows:
$Car = new Auto;
Moving the car can be done with the following line:
$Car->move(4);

PHP Introduction

PHP stands for Hypertext Preprocessor and is used as a scripting language that is embedded in HTML and runs on the web server. The PHP code is run on the server when the page is requested
Anyone who knows HTML and the C or C++ language can easily program PHP. PHP uses much of the same syntax of C, but is much easier to use and provides access to variables and their values as submitted using HTML forms without the need to parse information. Also PHP is designed to work easily with most SQL servers including the open source SQL server, MySQL.
PHP code is placed in the body of HTML code. It may be placed in HTML code as follows:
<php
echo "This is a test of PHP!";
?>
The above example will output the quoted text on the HTML page where the PHP code is embedded.
Many webservers support PHP out of the box although depending on the version, they may not support the latest version of PHP (Currently 4). If using PHP on the web, it is wise to run the latest version since it has some security enhancements. If you're just using PHP to learn on a local network using the latest PHP version is not as imperative. For example the Apache webserver that comes with Redhat Linux version 6.1 supports PHP3. Depending on how the webserver is setup, it may be required to name the HTML files that contain PHP code with an extension like ".php4".


Documentation

This manual is a brief synopsis of information as an aid to learning PHP. It provides basic PHP information, then provide examples of some useful PHP functionality including sessions, cookie use, sending mail and using it with SQL. It is not intended completely cover all aspects of PHP. Also, it is assumed that the reader is familiar with HTML and languages similar in type to C or Perl. Much PHP syntax is similar to the C programming language. To supplement this document, the reader should refer to the documents page in the weblinks PHP section for available online and downloadable documentation about PHP.
This document and the documentation at the PHP.org Document Section should be all a reader needs to learn PHP. Specifically the large downloadable PHP Manual which is in both PDF and HTML format is an excellent reference manual outlining the many PHP functions by category.


PHP Syntax

PHP statements end with a semicolon.
PHP supports comments the same as C and C++ using the methods shown below:
<?php
// This is a comment
echo "This is a test of PHP!";
?>
<?php
/* Line 1 of this comment
Line 2 of this comment */
echo "This is a test of PHP!";
?>

PHP Variables

  • PHP variable type is determined by the way in which it is used (context).
  • Variable names begin with a dollar sign, $, followed by a letter, then more letters or numbers.
Supported variables include integers, floating point numbers, strings, arrays, and objects.

Predefined Variables

There are additional predefined PHP variables defined in a file called "php.ini". Variables defined in HTML forms are available to the PHP file that the form is submitted to using the HTML form "action" attribute. Also if the PHP document has been called using a HTML form, a variable named $submit is available and may be tested to see if it exists. If it exists, an if statement may be used to display one set of HTML rather then the HTML that would be displayed if it does not exist. The phpinfo() function may be used to get a list of predefined variables.

Typecasting

Typecasting is performed with the type written in parenthesis as follows:


$i = (int) $myrealvalue;
Supported typecasts include (int), (array), (object), (string), (real), (double), and (float).

PHP Array Variables

PHP Array variables may be defined in the following manner:
$tree = array("trunk", "branches", "leaves");
In this case the value:
tree[0]
evaluates to the string "trunk". The statement:
$tree[3]="nuts";
sets a fourth array value to "nuts". In this way, the array, tree, may be dynamically expanded.
An array can be created and expanded in the following manner.
$car[ ]="body";
$car[ ]="engine";
$car[ ]="transmission";
$car[ ]="tires";

String Concatenation

Strings can be added to each other or additional values may be added to a string using the append, "." operator as follows:
echo "The value of my variable is: " . $myvariable;

Operators

The math and logical operators are the same as the C programming language. Variables may be pre-incremented or post incremented or decremented with commands like "++$a;" which does a pre increment.

Monday, December 20, 2010

Animate An Underground Map Without Keyframes In Motion 4


 OtterBox Defender Case for iPhone 4 (Black)Decision PointsDecision PointsDecision PointsDecision PointsIn this tutorial you will learn how to create and animate the map of your favorite city underground with Apple Motion 4. Behaviours will be our friends to avoid the use of keyframes. They are one of the most powerful tools in Motion to speed up your work.

Preview

Want access to the full AE project files and assets for every tutorial on Aetuts+, including this one? Join Ae Premium for just $9/month. You can view the final effect p
review video below.TutorialStep 1First of all, create a new Motion project and import your reference map into the group that Motion creates by default. In the properties tab (F1) scale it to fit it into your window and change its opacity to 50%.Step 2In the layers panel (F5 if it’s not visible), create a new group and name it lines. Select your bezier tool (B). In the HUD window (F7), select outline, pick up the colour of the line you want to trace (in that case RGB: 0, 174, 236) and a width of 5. Start tracing the first line mantaining ths shift key down to have perfect vertical and horizontal lines. You can zoom in to get more precision. Once your done with tracing your line, press the enter key.Step 3In your layers panel, select your new line, name it line 1 and change its roundness to 2 in the HUD. Go to inspector>shape tab>style (or F4 and style tab) and change the start and end caps to “round”.Step 4Repeat steps 2 & 3 for all your lines. I choosed to skip the line 12, the R one and the ML1 & ML2 because of their lack of interaction with other lines. Here are the colors I used as R,G,B: line 2 (226, 27, 6); line 3 (255, 217, 0); line 4 (151, 92, 38); line 5 (152, 190, 17); line 6 (175, 175, 158); line 7 (242, 149, 61); line 8 (224, 170, 184); line 9 (148, 140, 188); line 10 (7, 75, 142); line 11 (4, 152, 59). This is what you get after drawing all your lines (I hid the reference map to have a better look at what you get).Step 5Now we have to follow creating our map’s elements by drawing the starts/ends of lines and the interchanges. You have two way of doing it. The first one is using Motion’s circle tool with a white fill and a black outline of 1. The other one is using Illustrator and Motionsmart’s Illustrator path to Motion shape script. This is a small script that allows you to export Illustrator paths as Motion shapes. This allows you to create elements easier and with more control but only works with paths with connected points (for example, it doesn’t work with a donut). You don’t need to know how to manage Illustrator to get it. So let’s go on with Illustrator to try it. In Illustrator, create a new document and go to file>place and select your map to have it as reference.Step 6As you will get it as a Motion shape, you just need to create one copy of each kind of interchange. Start with the first one creating a circle with a white fill and a black outline with the circle tool (L).Step 7Duplicate it and move it to the right mantaining the shift key down to keep them aligned horizontally.Step 8Select your two circles, go to the pathfinder and press the add button and then expand.Step 9Your already done in Illustrator with that kind of interchanges. You now need to save it as a motion shape. With your path selected, go to file>scripts>export as motion shape. Name it 2circular and press ok. This automatically creates a Motion shape on your desktop. You can now move it to your working folder.Step 10Create now the other kinds of interchanges using the same way. For example, the 3 lines eliptical cross is made with a rectangle and 2 circles. You can use guides to make things easier. I moved my elements a bit down to show the source and the elements used to copy it.Step 11Once again, thanks to the pathfinder tool, group your elements into a unique one by pressing the add button and then expand. As done in step 9, export it as motion shape and name it 3eliptical.Step 12You now know all what you need to create the other six kinds of interchanges. Here you can see all of them with their relative names.Step 13Now you’re done with Illustrator, go back to Motion. Create a new camera. In the pop-up window, select “switch 2D groups into 3D groups”. Change the view to perspective (ctrl+P). This allows you not to have that crappy pixel effect by zooming in. Create a new group above the lines one, name it starts-interchanges and change its opacity to about 25%. In the file browser panel (cmd+1), locate the folder containing the shapes you made in Illustrator (if you didn’t move them, they still are on the desktop). You now have to drag as many copies of each one as requiered by your reference map into your new group and position them according to your reference map. Take care of the Z position of each element and of the group to be 0. You can zoom in for more precision. Don’t forget to name them to find them easier after. Here you have the result of all your starts and interchanges positioned with full opacity for a better preview.Step 14By default, the shapes you exported from Illustrator just have an outline so select all the shapes you just positioned and activate the white fill in the HUD or in the inspector>shape>style tab.Step 15Last step in the creation of the map: the colored points. Create a new group above the starts-interchangesand name itpoints. With the circle tool selected (C), go to the start of the first line and draw a circle in the middle of the station with the same color of the station line. Once again, be carefull of the Z position of the point you just created and of the points group to be 0.Step 16Now duplicate that point nine times and place your copies along the line 1.Step 17Duplicate again as many times as needed and place each point in a start or interchange to finish your map. Don’t forget to change the color accordingly to the lines! You should end with 97 points. Once done with placing points, you can turn the starts-interchanges opacity to 100% and hide your reference because you don’t need it for now.Step 18Go to Edit>project properties… (cmd+J),change duration to 30 seconds, change the background color to a soft grey (R=G=B=228) and the background to solid.Step 19Now it’s time to start animating that map. You first have to know which will be your travel plan. After a small research, I found a path that follows all the lines. Starting at south in line 11, then line 6 to “pacifico”, line 1 to “Sol”, line 2 to “plaza España”, line 10 to “Gregorio Marañon”, line 7 to “pueblo nuevo”, line 5 to “Nuñez Balboa”, line 9 to “colombia”, line 8 to “mar de cristal”, line 4 to “argüelles” and finally line 3 to the south.Step 20It’s better to start with all our lines, points and interchanges hidden. So go to the last frame, select everything but the camera and go to mark>mark in (I).Step 21Go back to the start point of the project, select the interchange named la peseta and press I. Do the same with the corresponding green point of line 11. With that point still selected, go to add filter>glow>bloom. In the filter properties tab (F3), change the settings as shown below. With the bloom effect selected, go to frame 8 and press O to mark out the effect.Decision Points


Step 22

With the green point (or the bloom filter) still selected, go to add behaviour>parameter>ramp two times and set it as shown below. Go to frame 5, select ramp and press O, then select ramp 1 and press I, then go to frame 8 and with ramp 1 still selected press O. You now have the lighting animation done without any keyframe.

Step 23

In the layer panel, select your effect and your two behaviours, press cmd+D to duplicate them, then drag them to “la peseta” interchange.

Step 24

Go to frame 5, select line 11 and press I. Go to add behaviour>parameter>ramp and set it as shown below. This will act as the classical write on effect. By retiming the behaviour, you can adjust the speed of the effect. So select the ramp behaviour, go to frame 32 and press O.

Step 25

Now we have all we need to do the whole animation quite fast. I chose to first create the animation and then work with the interchanges. So go to frame 37, select line 6 and press I. We start moving line 6 5 frames after line 11 arrives because of the glowing effect. Add two ramp behaviours to first and last point offset and set it as shown below. Values may change depending on how you create the lines. The important point is to get your line reduced to 1% (sum the offset and get 99%. Here 73+26=99) and in the good spot.

Step 26

Retime each behaviour according to how far it as to go. the 26% one as to be about three times faster than the 73% one for each part to have the same speed. Go to frame 63, select ramp 1 and press O. Then go to frame 110, select ramp and press O.

Step 27

Go to frame 63, when line 6 cross line 1 where we want to follow this one, select line 1 and press O. As we did before, add two ramp behaviour as in step 25. Below are the values I used. Once again retime them. I used frame 84 for ramp and frame 238 for ramp 1 as out points.

Step 28

Repeat steps 25 and 26 for all the lines. You can use the reference map to show when lines cross. Below are my settings for each line and their timings.
line 2: Start frame:127; ramp end frame: 161; ramp 1 end frame:188;
line 10: Start frame:143; ramp end frame: 289; ramp 1 end frame:292;
line 7: Start frame:213; ramp end frame: 277; ramp 1 end frame:349;
line 5: Start frame:295; ramp end frame: 465; ramp 1 end frame:321;
line 9: Start frame:338; ramp end frame: 436; ramp 1 end frame:438;
line 8: Start frame:376; ramp end frame: 421; ramp 1 end frame:428;
line 4: Start frame:389; ramp end frame: 524; ramp 1 end frame:404;
line 3: Start frame:529; ramp end frame: 544; ramp 1 end frame:664;

Step 29

Now the lines are well timed, we have to place the interchanges. Once again, use the reference map and each time a line cross an interchange, select this one and press I. Here is what your timeline should look like.

Step 30

Repeat step 29 with the points. Do it line by line to avoid mistakes.

Step 31

Another repetitive task: giving all points the glowing effect. Select the effect and the two behaviours of the first point, then press the option key and drag them to the second point. You’ll see that they all start at the same time, so you’ll have to drag your ramp 1 copy six frames ahead to keep the effect working.

Step 32

Repeat step 31 for all points and interchanges. To do it quite fast, first copy all your effects and behaviours and then select all the ramp 1 copy behaviours by clicking on the first you want to select and then, maintaining the command key down, click on all the others behaviours. By doing it this way, you can move all of them at the same time. You should be done with the animation of the map. Play back to verify that all is OK. At frame 135, you should have something like this.

Step 33

Below the lines group, create a new group and name it BG. Then go to library(cmd+2)>Generators and drag a gradient into your new group. Change its Z position to -5 then active reflection and set the reflectivity to 44% and blur amount to 11 and set it as shown below.

Step 34

Select your camera and set it as shown below.

Step 35

Go to the first frame, select your camera, go to add behaviour>basic motion>motion path. Go to the last frame to see all your network and in front view, move the two points to the start and end of line 11. It doesn’t need to match exactly. Then go to frame 32 and with your behaviour selected, press O.

Step 36

Go to frame 37 and repeat step 35 with next line. Before moving points, press O. This action locates your first point in the same place than the last point of your previous behaviour.

Step 37

Repeat step 36 for each line. Don’t forget to retime each behaviour before creating another one. If you need to had points to any path, just mantain the option key down and click on the path. You can convert the interpolation of the points to linear or let them as smooth (by default). Here is the path I get.

Step 38

Go to first frame, select your camera and in active camera view, decrease the y position as you can see a black point.

Step 39

Go a bit before the final of the animation, around frame 650, and creat a new group between the camera and the points group. Go to front view and create a rectangle to mask the whole map. Once you’re done, change its opacity to 0% and its position to 0, 0, 0.

Step 40

Select your camera, go to add behaviour>camera>framing and then press I. Drag and drop your rectangle in the target window of the behaviours tab, change the position transition to 45% and the rotation transition to 15% to keep the final of the animation on screen as your camera is rotating.

Step 41

Go to last frame, select all groups and press O. Then go to add behaviour>basic motion>fade in/fade out. Then set fade in to 0 and fade out to 25 for each one.

Step 42

Go to file>export (cmd + E) and choose export: Quicktime movie, use: HDV 720p25 movie. Then press options… In the output tab, that resolution is set to full, camera: actve camera, reflections is on and render quality: best. Then press OK and press export. You can use other settings according to your needs but take care of letting the reflections on if you want them to appear in your export.
Well, I hope you enjoyed my first Apple Motion tutorial (in fact it’s my first tutorial ever).