0

A Very Nice PHP Array Technique

Introduction

You properly already knew the following code:

$strings = array();
$strings[] = "apple";
$strings[]="bamboo";
$strings[]="cat";

This will contain an array of strings:

array(1=>"apple", 2=>"bamboo", 3=>"cat");

However, this is not very useful for multi-dimensional arrays where each array in a parent array contains the same keys and different values like the database array. This is where associative arrays come into play. The code below uses the same technique as above without using the array_push function.

Source Code

foreach ($strings as $row) {
 foreach ($row as $col=>$val) {
  $data[$col] = $val;
 }
}

Explanation

As you can see from the code, each array in the $strings array is copied into a new $data array. I can then use this newly copied array just after the end of second foreach loop to do something. For example, insert it into another database to change the database driver (MySQL to SQLite, for example).

Please share it in the comments below if you have any other uses for this technique.

0

Writing a New Class

I have been writing and testing a new PHP class today to make me easier to create my new site menu bar called menu class. It contains a nested unordered list and a for loop to create the sub-menus. I wrote a couple of variables that use explode function to convert the input values to arrays. Here is the code I have written so far:

<?php
class menu {
    function  __construct() {
            // Output the menu
        echo "<div id='nav'>n";
        echo "<ul>n";

        $this->item("Home", "/");

        $this->item("Blog", "blog");

        $this->item("Portfolio", "portfolio",
                "Resume=>resume,
                 About Me=>about");

        $this->item("Projects", "projects",
                "ICAP<br />Interagency Coalition on Adolescent Pregnancy=>icap");

        $this->item("School Assignments", "assignments",
                "CA 272<br />Pro Website Dev=>ca272,
                 CA 282<br />PHP & MySQL=>ca282,
                 CA 288<br />Adv ColdFusion=>ca288,
                 CS 110<br />Computer Concepts=>cs110");

        echo "</ul>n";
        echo "</div>n";
    }

    function item($menuItem, $linkLocation, $subItems="") {
        echo "<li>n";
        echo "<a href='{$linkLocation}' title='{$menuItem}'>$menuItem</a>n";
            // Insert the sub-menu items if there is one
        if (!empty($subItems)) {
            $this->submenu($subItems);
        }
        echo "</li>n";
    }

    function submenu($itemaLink) {
        $itemaLinks = explode(",", $itemaLink);
        echo "<div class='submenu'>n";
        echo "<ul>n";
        for ($i=0; $i", $itemaLinks[$i]);
                    // This is used for my courses names
                $title = explode("<br />", $itemLink[0]);
                if(sizeof($title) == 1) {
                    $title[1] = $itemLink[1];
                }
                echo "<li>n";
                echo "<a href='{$itemLink[1]}' title='{$title[1]}'>{$itemLink[0]}</a>n";
                echo "</li>n";
            }
        }
        echo "</ul>n";
        echo "</div>n";
    }
}
?>

Note the $itemLink variable from the code above. This is based on the array format. Equal greater than (=>) symbol is variable and value connector in an array. This makes me easier to remember to add a link to the corresponding item. I also added $title array later in the process to differentiate between course title (e.x. CA 288) and course name (e.x. Advanced ColdFusion Development). You can see the example on my beta site. Note that I have not added any JavaScript to animate the menu. I will add MooTools-based animation later after I complete writing this menu class.

0

Use Array to Populate the form with PHP

When I was doing my practice final for the PHP class today, I came across several problems for easier way to populate the form, especially with check box and option form controls. These two controls need to be repeated each time when new items were added to the list. Of course I could copy and paste the previous statement and edit it accordingly, but I want to make it easier by just input the new items into the appropriate arrays. Here is what I did to the multiple selection control:

<select multiple size="5" name="skills[]" id="Skills">
    <?php
        $selected = new prefilll();
        $webprogramming = array("AJAX","ColdFusion","HTML 5","JavaScript","JSP","PHP");
        $computerprogramming = array("Basic","C/C++","Java","Linux");
        $skillset = array("Web Programming"=>$webprogramming,"Computer Programming"=>$computerprogramming);
        foreach($skillset as $skillNum=>$skillsets) {
            echo "<optgroup label="$skillNum">n";
            foreach($skillsets as $programmingSkill) {
                echo "<option";
                echo $selected->selected("skills",$programmingSkill);
                echo " value="$programmingSkill">{$programmingSkill}</option>n";
            }
            echo "</optgroup>n";
        }
    ?>
</select>

And here is the check box control:

<?php
     $counter = 0;
     $checked = new prefilll();
     $jobtypes = array("full"=>"Full Time","part"=>"Part Time","weekdays"=>"Weekdays","weekends"=>"Weekends");
     foreach($jobtypes as $labelFor=>$values) {
         $counter++;
         echo "<input type='checkbox' name='jobtypes[]' value='{$values}' id='{$labelFor}'" . $checked->checked("jobtypes", $values) . " />n";
         echo "<label for='{$labelFor}'>{$values}</label>n";
         if ($counter == sizeof($jobtypes) / 2) {
             echo "<br />n";
         }
     }
?>

Note that I used a class in the above code segments, prefill. This class is used to reselect the items in the check box and option controls if there is a validation error.

Following is the code for the prefill class:

class prefilll{
    function selected($items,$Item) {
        if (isset($_POST[$items])) {
            $items = $_POST[$items];
            if (in_array($Item, $items)) {
                    $Selected = " selected";
                }
            else {
                $Selected = "";
            }
        }
        else {
            $Selected = "";
        }
        return $Selected;
    }
 function checked($items,$Item) {
        if (isset($_POST[$items])) {
            $items = $_POST[$items];
            if (in_array($Item, $items)) {
                    $checked = " checked";
                }
            else {
                $checked = "";
            }
        }
        else {
            $checked = "";
        }
        return $checked;
    }
}

You can download the above source code from here along with the whole source file if you want to experiment with it yourself.