List of PHP array functions

December 8th, 2009

array_change_key_case — Changes all keys in an array
array_chunk — Split an array into chunks
array_combine — Creates an array by using one array for keys and another for its values
array_count_values — Counts all the values of an array
array_diff_assoc — Computes the difference of arrays with additional index check
array_diff_key — Computes the difference of arrays using keys for comparison
array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a ser supplied callback function
array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
array_diff — Computes the difference of arrays
array_fill_keys — Fill an array with values, specifying keys
array_fill — Fill an array with values
array_filter — Filters elements of an array using a callback function
array_flip — Exchanges all keys with their associated values in an array
array_intersect_assoc — Computes the intersection of arrays with additional index check
array_intersect_key — Computes the intersection of arrays using keys for comparison
array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
array_intersect — Computes the intersection of arrays
array_key_exists — Checks if the given key or index exists in the array
array_keys — Return all the keys of an array
array_map — Applies the callback to the elements of the given arrays
array_merge_recursive — Merge two or more arrays recursively
array_merge — Merge one or more arrays
array_multisort — Sort multiple or multi-dimensional arrays
array_pad — Pad array to the specified length with a value
array_pop — Pop the element off the end of array
array_product — Calculate the product of values in an array
array_push — Push one or more elements onto the end of array
array_rand — Pick one or more random entries out of an array
array_reduce — Iteratively reduce the array to a single value using a callback function
array_replace_recursive — Replaces elements from passed arrays into the first array recursively
array_replace — Replaces elements from passed arrays into the first array
array_reverse — Return an array with elements in reverse order
array_search — Searches the array for a given value and returns the corresponding key if successful
array_shift — Shift an element off the beginning of array
array_slice — Extract a slice of the array
array_splice — Remove a portion of the array and replace it with something else
array_sum — Calculate the sum of values in an array
array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
array_udiff — Computes the difference of arrays by using a callback function for data comparison
array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
array_uintersect — Computes the intersection of arrays, compares data by a callback function
array_unique — Removes duplicate values from an array
array_unshift — Prepend one or more elements to the beginning of an array
array_values — Return all the values of an array
array_walk_recursive — Apply a user function recursively to every member of an array
array_walk — Apply a user function to every member of an array
array — Create an array
arsort — Sort an array in reverse order and maintain index association
asort — Sort an array and maintain index association
compact — Create array containing variables and their values
count — Count all elements in an array, or properties in an object
current — Return the current element in an array
each — Return the current key and value pair from an array and advance the array cursor
end — Set the internal pointer of an array to its last element
extract — Import variables into the current symbol table from an array
in_array — Checks if a value exists in an array
key — Fetch a key from an array
krsort — Sort an array by key in reverse order
ksort — Sort an array by key
list — Assign variables as if they were an array
natcasesort — Sort an array using a case insensitive “natural order” algorithm
natsort — Sort an array using a “natural order” algorithm
next — Advance the internal array pointer of an array
pos — Alias of current
prev — Rewind the internal array pointer
range — Create an array containing a range of elements
reset — Set the internal pointer of an array to its first element
rsort — Sort an array in reverse order
shuffle — Shuffle an array
sizeof — Alias of count
sort — Sort an array
uasort — Sort an array with a user-defined comparison function and maintain index association
uksort — Sort an array by keys using a user-defined comparison function
usort — Sort an array by values using a user-defined comparison function

PHP Regular expression usng preg_match and preg*

December 8th, 2009

Regular expressions are a powerful way of dissecting and retrieving values from text strings. 

Below is a table of some of the commonly used expressions.

xxx The string “xxx”
^xxx “xxx” at the start of a string
xxx$ “xxx” at the end of a string
^xxx$ “xxx” when it is alone on a string
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any character that is not a uppercase letter
(me|you) Matches either “me” or “you”
[a-z]+ One or more lowercase letters
[0-9\.\-] Аny number, dot, or minus sign
^[a-zA-Z0-9_]{1,5}$ Any word of at least one and up to 5 letters numbers or _
([ka])([rm]) km, kr, ar, or am
[^A-Za-z0-9] Any symbol (not a number or a letter)
([A-Z]{9}|[0-9]{4}) Matches nine letters or four numbers

How to turn on PHP Error Reporting

December 8th, 2009

To turn on Error reporting in PHP, within your code add the following 2 lines.

ini_set(”display_errors“,”2“);
ERROR_REPORTING(E_ALL);

This will report errors that won’t affect your code running. For instance, if($_GET['errid']) will return false if $_GET['errid'] is not set but will show as an error if error reporting is on.  You should use isset($_GET['errid']) first.

How to move an element up and down on a web page using javascript.

December 7th, 2009

The problem I encountered was that I needed to add an element to the webpage when I clicked on an image.  I then wanted to move the element up and down, enter text into a text box and delete the item.  For each image I added I would generate a line with each of these functions with it.

Once I had added the lines, put them in the order I wanted by moving them up and down, I then wanted to save them to the database in the order that they now appeared on the screen.  I decided to create the form elements from the element lines and then submit the form.

Below is the Javascript.

 

var lorder = 100;
function compile_board() {

 var board = document.getElementById(’board’);
 var myForm = document.getElementById(’theForm’);
 
 for(var i=0; i<board.childNodes.length; i++){

  var xx=board.childNodes[i].getElementsByTagName(’div’)[1].getElementsByTagName(’textarea’);
  var zz=board.childNodes[i].getElementsByTagName(’div’)[4].getElementsByTagName(’input’);
  html=’<input type=”hidden” name=”lines[]” value=”‘ + i + ‘|’ + zz['0'].value + ‘|’ + xx['0'].value +’”>’;
 
  myForm.innerHTML = myForm.innerHTML + html;
 }
 
 myForm.submit();
}
function add_pic( picno ){

 lorder = lorder +1;
 var board = document.getElementById(’board’);
 var a = document.createElement(’div’);
 board.appendChild(a);
 a.setAttribute(’class’,'boardline’);
 a.setAttribute(’id’,'o’+lorder);
 
 html= ‘<div style=”float:left;padding:5px 10px 2px 5px;width:110px;”><img src=”getsnap.php?picid=’ + picno + ‘&amp;typ=tn” alt=”" /></div><div style=”float:left;padding-top:5px;”><textarea name=”pic_text” size=”50″ maxlength=”50″ type=”text” rows=”5″></textarea></div><div style=”float:left;padding:20px 0 0 50px;”><img style=”cursor:pointer” src=”http://domain.com/javascript/images/up.jpg” onclick=”move_line(’+lorder+’,1);” />&nbsp;&nbsp;<img style=”cursor:pointer” src=”http://domain.com/javascript/images/down.jpg” onclick=”move_line(’+lorder+’,2);” /></div><div style=”float:right;”><img style=”cursor:pointer” src=”http://domain.com/javascript/images/x.jpg” height=”100″ onclick=”del_line(’ + lorder + ‘);” /></div><div><input type=”hidden” name=”picno” value=”‘ + picno + ‘” /></div>’;
 a.innerHTML = html;
 
}
function del_line( lorder ){

 var board = document.getElementById(’board’);
 var lid = document.getElementById(’o'+lorder);
 board.removeChild(lid);

}
function move_line( lorder , Direction ){
 var board = document.getElementById(’board’);
 var lid = document.getElementById(’o'+lorder);
  
  
 if((Direction == “1″)  ) {
  prev = get_previoussibling(lid);
  if (prev != null) {
   board.insertBefore(lid,prev);
  } 
 } else if((Direction == “2″) ){
  prev = get_nextsibling(lid);
  if (prev != null) {
   insertAfter(board,lid,prev);
  } 
 }//else if   
 

}

function insertAfter(parent, node, referenceNode) {
  parent.insertBefore(node, referenceNode.nextSibling);
}

function get_previoussibling(n)
{
 var x=n.previousSibling;
 if (x != null) {
  while (x.nodeType!=1)
   {
    x=x.previousSibling;
   }
  return x;
 }
}

function get_nextsibling(n)
{
 var x=n.nextSibling;
 if (x != null) {
  while (x.nodeType!=1)
   {
    x=x.nextSibling;
   }
  return x;
 }
}

I came across many problems but got there eventually.  Below is the Smarty template I used to generate the HTML for the page.  This would include the building of any of the element lines that were already in the database.

If you are not familiar to Smarty to should still be able to get an idea of what is going on.

<script type=”text/javascript” src=”{$DOC_ROOT}javascript/visionboard.js”></script>

<div style=”vertical-align:top;” >
 {assign var=”page_hdr01_text” value=”Create Vision Board”}
 {assign var=”page_title” value=$page_hdr01_text}
 {include file=”page_hdr01.tpl”}
 <div style=” padding-top:4px;”>
   {if $smarty.get.msg != ”}
    {include file=”display_error.tpl” }
   {/if}
            <div style=”text-align:center;” align=”center”>
            {section name=”sec” loop=$max_picture_cnt start=”0″ step=”1″}
                <div style=”text-align:center;”>
                    <img src=”getsnap.php?picid={$data[$smarty.section.sec.index].picno|default:$nextpic}&amp;typ=tn” alt=”" id=”{$data[$smarty.section.sec.index].picno}” onclick=”javascript: add_pic(’{$data[$smarty.section.sec.index].picno}’);” style=”cursor: pointer;” />
                </div>
                <div style=”clear:both;padding-bottom:2px;”></div>
            {/section}
            </div>
            <div id=”board”>{foreach from=$lines key=key item=val name=lines}<div id=”o{$key+1}”><div style=”float:left;padding:5px 10px 2px 5px;width:110px;”><img src=”getsnap.php?picid={$val.picno}&amp;typ=tn” alt=”" /></div><div style=”float:left;padding-top:5px;”><textarea name=”pic_text” size=”50″ maxlength=”50″ type=”text” rows=”5″>{$val.text}</textarea></div><div style=”float:left;padding:20px 0 0 50px;”><img style=”cursor:pointer” src=”http://domain.com/javascript/images/up.jpg” onclick=”move_line({$key+1},1);” />&nbsp;&nbsp;<img style=”cursor:pointer” src=”http://domain.com/javascript/images/down.jpg” onclick=”move_line({$key+1},2);” /></div><div style=”float:right;”><img style=”cursor:pointer” src=”http://domain.com/javascript/images/x.jpg” height=”100″ onclick=”del_line({$key+1});” /></div><div><input type=”hidden” name=”picno” value=”{$val.picno}” /></div></div>{/foreach}</div>
            <div>
            <form id=”theForm” name=”frmEditUser” method=”post”>

            <!– This is where the form is built when submit is pressed –>
    <input type=”hidden” name=”action” value=”submit” />
    <input onclick=”compile_board();” type=”button” value=’{lang mkey=’submit’}'/> <input onclick=”reset_board();” type=”reset” value=”{lang mkey=’reset’}”/>
            </form>
            </div>
            <div style=”clear:both;padding-bottom:2px;”></div>
 </div>
</div>

 

You may notice I use getsnap.php within the image tag.  This is because my images are stored in a database so I have to retrieve them and convert them for display first.

Beware when using this code that there is no white space between the TAG <div id=”board”>or you will get errors due to white space being interpretted as the invisible TAG called text.  The applies to the code in the variable html within the Javascript code.

Below is the PHP for storing and retrieving the lines.

<?php
if ( !defined( ‘SMARTY_DIR’ ) ) {
 include_once( ‘init.php’ );
}
include ( ’sessioninc.php’ );
$userid = $_SESSION['UserId'];

$lines=$_POST['lines'];

$board_id = $DB->getOne(’select board_id from ! where userid = ?’, array( ‘_board’, $_SESSION['UserId']) );

if($_POST['action']==’submit’) {

 if(!($board_id)){
  $DB->query( ‘INSERT into ! (userid) values(?)’, array( ‘_board’,  $userid ) );
  $board_id = $osDB->getOne(’select board_id from ! where userid = ?’, array( ‘_board’, $userid ));
 }
    $osDB->query(’delete from ! where board_id = ?’, array(’_board_lines’, $board_id) );
 
 foreach ($lines as $k => $v) {
 
  $order_pic = explode(”|”,$v);
  $osDB->query( ‘INSERT into ! ( board_id, picno, line_order, text ) values ( ?, ?, ?, ?)’,
       array( ‘_board_lines’,  $board_id, $order_pic[1] ,$order_pic[0] ,$order_pic[2] ) );
 }
}

$temp =& $DB->getAll(”select * from ! where userid = ? order by picno”, array( USER_SNAP_TABLE, $_SESSION['UserId'] ));

if($board_id){
 $board_lines = $DB->getAll(’SELECT * FROM ! WHERE board_id = ? ORDER BY line_order’, array( ‘_board_lines’, $board_id ) );
}
$index = 0;

foreach( $temp as $index => $row ) {

 $data []= $row;
}

unset($temp);

//Assign template variables to Smarty
$t->assign(’max_picture_cnt’, count($data));

$t->assign(’lines’, $board_lines);

$t->assign ( ‘data’, $data );

unset($data);

// *******  This line below is the above template file.  **********

$t->assign(’rendered_page’, $t->fetch(’createboard.tpl’) );

//Display template
$t->display(’index.tpl’);
?>