We'll be working with Drupal 5. To test all this php examples while working on Drupal: From create content, choose page (or story) and write the code betwwen the php tags, and dont forget to change the input format to php, otherwise the code will be stripped out.
Where to find PHP in Drupal:
- nodes
- blocks
- theme templates
- modules
Examples we used:
Example 1:
print "Hello World";
Example 2:
What is the difference between:
print 5+5;
and
print "5+5";
Example 3:
question mark operator
print 4<5 ? "true" : "false" ;
If the expression "4<5" evaluates to true, then the print command will print the first expression after the question mark, otherwise it will print the second one.
Example 4:
variables
$foo=5 ; print $foo ; print $foo*$foo ;
Example 5:
Drupal variable: if u add this line after any of the above examples, u'll get the code of the above examples displayed as a result.
print $code;
Example 6:
arrays:
print $_SERVER["HTTP_USER_AGENT"];
Example 7:
functions:
print_r($_SERVER) ;
to know the structure of the whole array.
Example 8:
We had a poll with node id = 55, and we wanted to know how many votes the 2nd choice got:
$node = node_load(55);
and we add
print_r($node);
to know the structure of this object.
to get the number of votes for the second choice, we add this line:
print "votes = ".$node->choice[1]["chvotes"];
Topics that we tackled in the first session:
PHP
PHP syntax:
- the php tags
- all statements end with ;
- strings must be between quotes
- variables start with $
PHP types:
- integers
- strings
- boolean
- arrays:
- we use indices to extract the different values from arrays: we but the index in square brackets.
- the index could be an integer or a string, and could also be a variable
- objects:
- we use attributes to deal with objects: $object->attribute
PHP commands:
PHP operators:
- equality == (if $a=$b, it is called assignment and it means put the value of $b in $a)
- comparison operators > and <
- question mark operator ?
- dot operator . for concatenating strings
PHP functions:
we also mentioned the variable scope and session.
Drupal:
Drupal variables:
- $code
Drupal functions:
HTTP variables: