Powerful PHP Array

PHP array functions indeed very powerful. Here’s couple tricks I usually used on my office projects when dealing with arrays.

Slurping Files and Trim each lines

slurping is reading the contents of file in a variables. It’s fast and efficient, but very resource hogging. Use it with careful

Instead of

$file = 'x.txt';
$lines = array();
$fp = fopen($file, 'r');
while(!feof($fp))
  if ($line = trim(fgets($fp, 1024)))
    $lines[] = $line;
fclose($fp);

Try to use this, its much clearer

$file = 'x.txt';
$lines = array_filter(array_map('trim', file($file)));

Unique Lines

Retrieve unique values from $array

$unique = array_unique($array);

Utilizing Arrays

Now how we can utilizing arrays, not just for storing data, we can use it for
doing so many boring things in programming and make it fun

Retrieveing Form Values

Using arrays, we can retrieve form values in just a couple of lines

$fields = array('username', 'password', 'confirmed_password', 'email');
foreach($fields as $field)
  $$field = isset($_POST[$field])
    ? trim(get_magic_quotes_gpc() ? stripslashes($_POST[$field]) : $_POST[$field])
    : '';

// now we can use it
if ($password != $confirmed_password)
  die('Invalid password!');

Building SQL statements with arrays

We usually concat string to build SQL statement, don’t, concat is dirty. Use array,
it much cleaner

$q = get_magic_quotes_gpc() ? stripslashes(@$_GET['q']) : @$_GET['q'];
$cat = get_magic_quotes_gpc() ? stripslashes(@$_GET['cat']) : @$_GET['cat'];

// add conditions
$where = array();
if ($q) $where[] = sprintf("text LIKE '%%%s%%'", addcslashes(mysql_real_escape_string($q), '%_?*'));
if ($cat) $where[] = sprintf("cat = '%s'", mysql_real_escape_string($cat));

// now build query string
$wherestr = empty($where) ? '' : ' where ' . implode(' and ', $where);
$sql = "select * from table $wherestr";
echo $sql;

That’s for now, you can explore another PHP array capabilities. Have fun!

10 komentar

  1. GuM bilang:

    Aahh.. yes..array technique.

    just like one-line-technique you gave me the other day to convert an array into a query string :D

    $arrQs = array(
    ‘username’ => ‘xxx’,
    ‘password’ => ‘xxx’,
    ‘name’ => ‘xxx’,
    );

    $o = array();foreach($arrQs as $k => $v){$o[] = urlencode($k) . ‘=’ . urlencode($v);}echo implode(’&’, $o);

    December 19th, 2006 at 15:07
  2. isdah bilang:

    very resource hogging

    weh buktine endi?

    December 20th, 2006 at 01:03
  3. ferdhie bilang:

    Lho, ndak percaya …

    December 20th, 2006 at 16:22
  4. isdah bilang:

    kasih script buat liat resource yang kepake’ dunk… *kedip2 sambil towel2 oweh*

    December 20th, 2006 at 17:47
  5. Aryo Sanjaya bilang:

    #Ambar:

    Lek iku sih masio 10 baris iso dadi 1 baris, asal disambung menyamping :p

    December 25th, 2006 at 14:20
  6. A320 bilang:

    Hi

    Take a look at this array. It represents a simple tree. I need that because
    the site i’m working on uses Smarty templates an there’s a way to do output
    the tree using ‘Smarty functions’

    $tpl->assign(”tree”,array(”element”=>array(array(”name” => “test1″,
    “element” =>
    array(array(”name” => “test1.1″),

    array(”name” => “test1.2″,

    “element” => array(array(”name” => “test1.2.1″),

    array(”name” => “test1.2.2″))))))));

    I took this example from smarty forum.
    Can you tell me how the function to make that array?

    March 4th, 2007 at 14:45
  7. ferdhie bilang:

    I never do any smarty jobs before, but it looks like you building a tree or something, try this functions, the drawback is that you must use a lot of reference passing, and PHP is so sucks when dealing with reference.

    function &add(&$array, $name)
    {
    $child = array(’name’ => $name);
    $array['element'][] =& $child;
    return $child;
    }

    $array2 = array();
    $root =& add($array2, ‘test1′);
    $child1 =& add($root, ‘test1.1′);
    $child2 =& add($root, ‘test1.2′);
    $child3 =& add($child2, ‘test1.2.1′);
    $child4 =& add($child2, ‘test1.2.2′);
    print_r($array2);

    March 4th, 2007 at 21:36
  8. A320 bilang:

    i think you don’t understand what i mean.
    i want to make tree level of some organization (ex:MLM).
    So i can see whos level below this id and also i can set the depest level to view.

    so when i want to see 3 level of my downline, the result should be like this
    A(level 1)
    ==A.1(level 2)
    ==A.2(level 2)
    B(level 1)
    ==B.1(level 2)
    ===B.1.1(level 3)

    A & B is my downline.

    Btw, thanx for your response.

    March 4th, 2007 at 22:00
  9. ferdhie bilang:

    The above example (add function) will build the array that passed to the $tpl, but if you generate the tree from a database, I’d suggest that your database should be like this:

    members
    - member_id
    - nama
    - parent_id

    now, use this func

    function list_member($parent=0)
    {
    $parent = intval($parent);
    $r= mysql_query(”SELECT * FROM member WHERE parent_id=’$parent’”);
    while($row = mysql_fetch_row($r))
    {
    list($member_id, $nama, $parent_id) = $row;
    echo “”, htmlspecialchars($nama);
    echo “”, list_member($member_id), “”;
    echo “”;
    }
    }

    // now we call them
    echo “”, list_member(), “”;

    now, you can modify it for returning an array with the add function above.

    March 5th, 2007 at 09:22
  10. A320 bilang:

    Wow!! I should try it soon……..
    Thanx for your help!!

    Hey, article you write above… its GREAT!!

    March 5th, 2007 at 10:45

Tinggalkan Komentar





*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word