Archive

Archive for the ‘PHP’ Category

PHP: Counting Arrays

September 17th, 2009

Recursive count() example

$food = array('fruits' => array(’orange’, ‘banana’, ‘apple’),
‘veggie’ => array(’carrot’, ‘collard’, ‘pea’));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

?>

PHP

Intro to Php Objects.

June 30th, 2009

I wrote up this quick little banking script to illustrate how to do simple object oriented programming in php5 using classes. Functions within a class are known as methods.

-JJ

class account_transact
{
    var $balance;
    var $account_type;
    var $amount;

    function get_bal($account_type)
    {
        if($account_type=='checking')
        {
            #query for sql to look up account
            $balance=100;
        }
        elseif($account_type=='savings')
        {
            #query for sql to look up account
            $balance=25;
        }
        return $balance;
    }
    function verify_account($account_type)
    {
        if($account_type=="checking" || $account_type=="savings")
        {
            #account verified
            return $account_type;
        }
        else
        {
            echo $account_type." is not a valid account";
            exit();
        }
    }
    function deposit($account_type, $amount)
    {
        $cur_bal=$this->get_bal($account_type);
        $new_bal=$cur_bal+$amount;
        print "Balance for “.$account_type.” is $”.$new_bal.”
“; } } //create new class instance $transaction=new account_transact(); //checking deposit $account=$transaction->verify_account(”checking”); $transaction->deposit($account,”5″); //savings $account=$transaction->verify_account(”savings”); $transaction->deposit($account,”-10″); ?>

More: http://www.php-editors.com/articles/simple_php_classes.php

PHP

Using Ternary PHP Conditionals (short hand)

February 26th, 2009

Standard php conditional:

  1. if (date("G") < 12) {
  2. echo 'Good morning';
  3. } else {
  4. echo 'Good afternoon';
  5. }

Shorthand…

  1. $greeting = (date("G") < 12) ? 'Good morning' : 'Good afternoon';
  2. echo $greeting;

(http://www.addedbytes.com/php/ternary-conditionals/)

PHP