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 Comments | [Put comments]

  1. gravatar GuM - December 19, 2006

    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);
  2. gravatar isdah - December 20, 2006

    very resource hogging
    weh buktine endi?
  3. gravatar ferdhie - December 20, 2006

    Lho, ndak percaya ...
  4. gravatar isdah - December 20, 2006

    kasih script buat liat resource yang kepake' dunk... *kedip2 sambil towel2 oweh*
  5. gravatar Aryo Sanjaya - December 25, 2006

    #Ambar: Lek iku sih masio 10 baris iso dadi 1 baris, asal disambung menyamping :p
  6. gravatar A320 - March 4, 2007

    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?
  7. gravatar ferdhie - March 4, 2007

    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);
  8. gravatar A320 - March 4, 2007

    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.
  9. gravatar ferdhie - March 5, 2007

    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.
  10. gravatar A320 - March 5, 2007

    Wow!! I should try it soon........ Thanx for your help!! Hey, article you write above... its GREAT!!

Reply to Comment #comment:321 by ferdhie