PHP: Arrays, associative arrays, and objects

A programmer can’t get by with simple variables alone.  Sometimes you need other tools.  Let’s take a look at three options that you have.

Arrays can be defined like

<?php
    $names = array('Joe', 'Steve', 'Jen', 'David');
?>

… or can be defined like

<?php
    $names[] = 'Joe';
    $names[] = 'Steve';
    $names[] = 'Jen';
    $names[] = 'David';
?>

… but defining a variable alone, won’t help you much.  You need to be able to see what the current value is, now.  Unfortunately, it wouldn’t help to simply echo your new array.  There is an alternative, though.  You can use print_r().

<?php
    $names[] = 'Joe';
    $names[] = 'Steve';
    $names[] = 'Jen';
    $names[] = 'David';

    print_r($names);
?>

If you only wanted to target one item in the array, you could do this, though …

<?php
    $names[] = 'Joe';
    $names[] = 'Steve';
    $names[] = 'Jen';
    $names[] = 'David';

    echo $names[0];
?>

Associative arrays are similar to normal arrays but instead of index numbers, you can use words.

<?php
    $colors = array('apple' => 'red',
                    'cheese' => 'white',
                    'leaf' => 'green');
    print_r($colors);
?>

You can reference your associative array elements like

<?php
    $colors = array('apple' => 'red',
                    'cheese' => 'white',
                    'leaf' => 'green');
    echo "Your cheese is {$colors[cheese]}.";
?>

PHP, unlike most languages that I have worked with in the past, doesn’t have a struct data type.  This is annoying but it sounds like PHP people get around that by using objects where you would normally use a struct.  An example would be

<?php
    class person {
        public $hair;
        public $eyes;
        public $gender;
    }
    
    $joe = new person();
    $joe->hair = 'brown';
    $joe->eyes = 'blue';
    $joe->gender = 'male';

    print_r($joe);
?>

I seems like it would work alright.

Leave a Reply

Your email address will not be published.