Duminda Chamara

Sunday, March 21, 2010

Array functions in PHP


Useful Array Functions In PHP

Following example shows you some useful php array functions.





How to get the number of elements in an array?

You can get the number of elements in the array using count() function in PHP.

It returns the number of elements as the return value.



<?php

$colors=array("Red","Green","Blue","Pink","Yellow");
print(count($colors)." elements in the array");

?>
Output:
5 elements in the array

How to count the frequency of array elements in PHP?

Some time you may want to count how many duplicate values in an array and their frequency.

In such case you can use array_count_values() function to find out them. Following example explains how to do it.



<?php

$shop_opend_days_for_month=array("Monday","Tuesday","Wednesday","Friday",

"Monday","Wednesday","Thursday","Saturday",

"Monday","Wednesday","Friday",

"Monday","Tuesday","Wednesday","Saturday");
print_r(array_count_values($shop_opend_days_for_month));
?>
Output:
Array ( [Monday] => 4 [Tuesday] => 2 [Wednesday] => 4 [Friday] => 2 [Thursday] => 1 [Saturday] => 2 )
Above function can count string and integer values only. otherwise it throws an warning
message 'Can only count STRING and INTEGER values!'

How to compare the difference of two arrays?

Suppose that there are two arrays and there are common elements to both arrays. Then you want to get unique values to the both arrays. In such case you can use array_diff() and array_merge() functions in php. Following example shows how to do it.



<?php

$colors1=array("Red","Green","Blue","Black","White","Orange");

$colors2=array("Red","Green","Black","Blue","Pink","White","Silver");
print_r(array_merge(array_diff($colors1,$colors2),array_diff($colors2,$colors1)));
?>

Output:
Array ( [0] => Orange [1] => Pink [2] => Silver )
array_diff() function compares array1 against array2 and returns the difference as an array.

array_merge() function merges the elements of one or more arrays together and returns an array with elements of input arrays.

How to combine two arrays?

Sometimes you may want to append one or more arrays in to one array. In such cases you can use array_merge() function to do it. Following example shows how to do that.


<?php

$colors1=array("Red","Green","Blue");

$colors2=array("Pink","White","Silver");

$colors3=array("Gold","Black","Orange");
print_r(array_merge($colors1,$colors2,$colors3));
?>

Output:

Array ( [0] => Red[1] => Green[2] => Blue[3] => Pink[4] => White[5] => Silver[6] => Gold[7] => Black[8] => Orange )

How to reverse the order of the values of an array?

You can reverse the order of the array elements using array_reverse() function in PHP. Following example shows how to do it.


<?php

$array=array("First","Second","Third","Forth","Fifth");
print_r(array_reverse($array));
?>
Output:
Array ( [0] => Fifth [1] => Forth [2] => Third [3] => Second [4] => First )

How to create an array with default values for it's elements?

Sometimes you may want to create an array which has default value to its elements. In such case you can use array_fill() function. Following example shows how to do it.


<?php

$colors = array_fill(0, 6,'White');

print_r($colors);
?>
Output:
Array ( [0] => White [1] => White [2] => White [3] => White [4] => White [5] => White )

How to add elements to the end of an array?

In some case you may want to add one or more elements to the end of an array. using php array_push() function you can do it. Following example shows how to do it.



<?php

$days = array("Sunday","Monday","Tuesday","Wednesday");

array_push($days,"Thursday","Friday","Saturday");
print_r($days);
?>

Output:
Array ( [0] => Sunday [1] => Monday [2] => Tuesday [3] => Wednesday [4] => Thursday [5] => Friday [6] => Saturday )

How to add elements to the beginning of an array?

In some case you may want to add one or more elements to the front of an array. using php array_unshift() function you can do it. Following example shows how to do it.


<?php

$numbers = array(4,5,6,7);

array_unshift($numbers,1,2,3);
print_r($numbers);
?>

Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )

How to calculate the sum of an array which contains integer or floating point values?

Sometimes you may want to calculate the sum of an array elements using array_sum() function. when you are using integer or floating point values in the array. For an example there is an array containing marks of a student according to the subjects. Then you can calculate the total marks and the total and average marks in convenient way instead of adding them one by one. Following example shows how to do this.



<?php

$marks = array('Maths'=>84,'Science'=>92,'English'=>64,'History'=>70,'Music'=>96);



print("Total marks for ".count($marks)." subjects = ".array_sum($marks)."<br>");
print("Average marks = ".array_sum($marks)/count($marks));
?>

Output:
Total marks for 5 subjects = 406

Average marks = 81.2


* array_sum() function works with only integer and floating point numbers.





Bookmark and Share



Try It!






 »   How to create random validation image in PHP
 »   How to get extension of a file using PHP
 »   How to upload and encrypt file in PHP
 »   How to upload files in PHP
 »   How to create arrays in PHP
 »   How to create thumbnail images in PHP
 »   How to connect MySQL Database in PHP







©-Copyright By Duminda Chamara  
JavaScript Validation  

How to create text file in PHP

How to create text file in PHP?

This tutorial explains you how to make text file in PHP
Create numeric, associative and multidimensional arrays in php

File handling is very important when doing programming. PHP has several methods to create text files. So you can make a text file in few steps. Before you creating files in your file system, you have to check whether the file exist or not. This prevents accidental file overwritten and data lost. Also you need have check enough permissions to write into the directory. You can simply use fopen() and fwrite() methods to create a file. It returns the number of bytes written to the file.


Demo - create text file in PHP?

File Name
Content
 

1. Create simple text file in PHP?

Above demo shows a live example for creating a text file. Its code as follows. This code creates a new file with the given file name. fopen() method is use to create a file. fwrite() method use to write a string to the file. You can specify the length of the string that need to write in to the file. This is a optional parameter. If you didn't specify the length, it means total length of the string should be write to the file. Please note you have to give correct file name that support your platform. In this example I have explained how to add line brakes to the file.

Note: You can use PHP_EOL constant to make a line break. It automatically get the appropriate line break for the platform. Or you can use "\n" or "\r\n" for add line breaks to the file.

fflush() is use to forces a write of all buffered content to the file. This is useful when you are dumping large content in to a file.



<?php

$fileName="D:\projects\simpleFile.txt";

if(file_exists($fileName)==false){
$myFile = fopen($fileName, 'w');//w indicates you can write text to the file

$textToWrite = "Creating text file in php is very simple!";

$line2 =PHP_EOL."This is line two of your text file";
$line3 =PHP_EOL."You can use \"\\r\\n\" to break lines in your file";

fwrite($myFile,$textToWrite,strlen($textToWrite));
fflush($myFile);
fwrite($myFile,$line2);
fwrite($myFile,$line3);

fflush($myFile);

fclose($myFile);
}else{
print("File already exists. Please select another name");
}


? >

2. How to append text to a existing file in php?

Sometimes you may need to append some new data to an existing file. Following example shows how to add new text to file and modify it. This will append text, at the end of the file.



<?php

$fileName="D:\projects\existing-file.txt";

if(file_exists($fileName)){
$myFile = fopen($myFile, 'a+');
$new_text = PHP_EOL."This is a new content";
fwrite($myFile,$new_text);
fclose($myFile);
}else{
print("File does not exists");
}

?>

3. Useful functions when creating files in php?

Note: Before you use those methods you have to check if the file exists or not.

$fileName="D:\projects\existing-file.txt";

(a). How to get the file size?

echo "File size is ".number_format((filesize($fileName)/1024),2).' Kb';

(b). How to get the file created time in php?

date_default_timezone_set("Asia/Kolkata"); //First you have to specify the time zone
echo "File created time : " . date("Y M d H:i:s", filemtime($fileName));

(c). How to get the last modified time of the file in php?

echo "Last Modified: " . date("Y M d H:i:s", filectime($fileName));

(d). How to get the last accessed time of the file in php?

echo "Last Accessed: " . date("Y M d H:i:s", fileatime($fileName));

Sunday, March 14, 2010

How to create tree view/menu


How to create tree view/menu?


Following example shows you how to create simple tree view/menu using javascript.


Now a days most web site designers use tree view navigation on their web pages. Creating a tree view is very simple. You need only simple javascript and little style sheet. In a tree view navigation there can be number of nodes and sub nodes. Following examples show how to create a tree view with one level node depth and tree view with depth of two levels. Like this example you can expand this program to any number of node depth.



Demo- Create tree view / menu using JavaScript.
 » 

How to create simple tree view/menu?

Node depth=1
  
»

How to create simple tree view/menu?

Node depth=2

Useful Web Sites
Search Engines
Social Networks
Encyclopedia


Sample Tree View
Sample Submenu 1
Sample Submenu 3
Sample Submenu 3



Bookmark and Share



Try It!







1. Example code for create tree view/menu in JavaScript.

JavaScript Code
<script type="text/javascript" language="javascript">

<!--
function hide_menu(node_id,menu_type){

var node_prefix="";

switch(menu_type){

case 1:{

node_prefix="node_";

}break;

case 2:{

node_prefix="main_node_";

}break;

}



var node=document.getElementById(node_prefix+node_id);

var node_status=document.getElementById(node_prefix+node_id+"_status");

var node_text=document.getElementById(node_prefix+node_id+"_title");
if(node_status.value=="1"){

node.style.display = "none";

}else{

node.style.display = "";

}

if(node_status.value=="1"){

node_status.value="0";

node_text.innerHTML="&#9658";

}else{

node_status.value="1";

node_text.innerHTML="&#9660";

}

return false;

}
-->

</script>
CSS Code
<style type="text/css">

.node_content{

padding-left:30px;

}

.node_title{

vertical-align:top;

}

.link_text{

font-family:Verdana, Arial, Helvetica, sans-serif;

font-size:10px;

text-decoration:none;

}

.link_text:hover{

text-shadow:#FFCC00;

font-weight:bold;

}

.node_title{

font-family:Verdana, Arial, Helvetica, sans-serif;

font-size:11px;

font-weight:bold;

text-decoration:none;

}

</style>
HTML Code
<html>

<head><title>How to create tree view in JavaScript </title>

</head><body>

<div id="myMenu">

<div id="node_title_1"><a href="javascript:void(0);" onclick="javascript:hide_menu('1',1);" class="link_text">

<span class="node_title" id="node_1_title">&#9660;</span></a><span class="node_title">Sample Tree Menu 1 </span>

<div id="node_1">

<div id="node_1_link_1" class="node_content">&bull;&nbsp;<a href="javascript:void(0);" class="link_text">Sample tree menu link 1 </a></div>

<div id="node_1_link_2" class="node_content">&bull;&nbsp;<a href="javascript:void(0);" class="link_text">Sample tree menu link 2 </a></div>

<div id="node_1_link_3" class="node_content">&bull;&nbsp;<a href="javascript:void(0);" class="link_text">Sample tree menu link 3 </a></div>

</div><input type="hidden" id="node_1_status" name="node_1_status" value="1" />

</div>

<div id="node_title_2"><a href="javascript:void(0);" onclick="javascript:hide_menu('2',1);" class="link_text"> <span class="node_title" id="node_2_title">&#9660;</span></a><span class="node_title">Sample Tree Menu 2 </span>

<div id="node_2">

<div id="node_2_link_1" class="node_content">&bull;&nbsp;<a href="javascript:void(0);" class="link_text">Sample tree menu link 4 </a></div>

<div id="node_2_link_2" class="node_content">&bull;&nbsp;<a href="javascript:void(0);" class="link_text">Sample tree menu link 5 </a></div>

<div id="node_2_link_3" class="node_content">&bull;&nbsp;<a href="javascript:void(0);" class="link_text">Sample tree menu link 6 </a></div>

</div><input type="hidden" id="node_2_status" name="node_2_status" value="1" />

</div>

<div id="node_title_3"><a href="javascript:void(0);" onclick="javascript:hide_menu('3',1);" class="link_text"> <span class="node_title" id="node_3_title">&#9660;</span></a><span class="node_title">Sample Tree Menu 3 </span>

<div id="node_3">

<div id="node_3_link_1" class="node_content">&bull;&nbsp;<a href="javascript:void(0);" class="link_text">Sample tree menu link 7 </a></div>

<div id="node_3_link_2" class="node_content">&bull;&nbsp;<a href="javascript:void(0);" class="link_text">Sample tree menu link 8 </a></div>

<div id="node_3_link_3" class="node_content">&bull;&nbsp;<a href="javascript:void(0);" class="link_text">Sample tree menu link 9 </a></div>

</div><input type="hidden" id="node_3_status" name="node_3_status" value="1" />

</div></div>

</body>

</html>
 



 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript



©-Copyright By Duminda Chamara
JavaScript Validation  

How to automatically check multiple checkboxes


How to automatically check/uncheck multiple checkboxes


Following example shows you how to automatically check or uncheck multiple checkboxes using simple javascript.
Some occasions you may want to check or uncheck more than one check box automatically using single mouse click. You can use simple javascript program to perform your need. You may have seen this in some web mail programs such as Gamil, Yahoo or Hotmail. Three you can check or uncheck multiple check boxes using single click. In this example check box and link used to make your selection.
Demo- Automatically check uncheck checkboxes using JavaScript.




Select at least one programming language
Check/Uncheck using checkbox   Check All
Check/Uncheck using link  Check All UnCheck All
Check/Uncheck using button  
Try It!
Bookmark and Share

1. Example code for check/uncheck multiple check boxes.

JavaScript Code
<script type="text/javascript" language="javascript">

<!--

function checkThemAll(chk){

var formName = "formMultipleCheckBox";

var checkBoxName="checkBoxesProgrammingLanguages[]";

var form = document.forms[formName];

var noOfCheckBoxes = form[checkBoxName].length;

for(var x=0;x<noOfCheckBoxes;x++){

if(chk.checked==true){

if(form[checkBoxName][x].checked==false){

form[checkBoxName][x].checked=true;

}

}else{

if(form[checkBoxName][x].checked==true){

form[checkBoxName][x].checked=false;

}

}

}

}

-->

</script>
HTML Code


<html>

<head><title>How to automatically check multiple check boxes using JavaScript </title>

</head><body><form id="formMultipleCheckBox" name="formMultipleCheckBox"> <table border="0">

<tr>

<td colspan="9">Select at least one programming language </td>

</tr>

<tr>

<td><label>

<input name="checkBoxesProgrammingLanguages[]" type="checkbox" id="checkBoxesProgrammingLanguages[]" value="1" />

Java</label></td>

<td><label>

<input name="checkBoxesProgrammingLanguages[]" type="checkbox" id="checkBoxesProgrammingLanguages[]" value="2" />

C++</label></td>

<td>&nbsp;</td>

<td><label>

<input name="checkBoxesProgrammingLanguages[]" type="checkbox" id="checkBoxesProgrammingLanguages[]" value="3" />

Python</label></td>

<td>&nbsp;</td>

<td><label>

<input name="checkBoxesProgrammingLanguages[]" type="checkbox" id="checkBoxesProgrammingLanguages[]" value="4" />

Perl</label></td>

<td>&nbsp;</td>

<td>&nbsp;</td>

<td rowspan="6">&nbsp;</td>

</tr>

<tr>

<td><label>

<input name="checkBoxesProgrammingLanguages[]" type="checkbox" id="checkBoxesProgrammingLanguages[]" value="5" />

PHP </label></td>

<td><label>

<input name="checkBoxesProgrammingLanguages[]" type="checkbox" id="checkBoxesProgrammingLanguages[]" value="6" />

VB.net</label></td>

<td>&nbsp;</td>

<td><label>

<input name="checkBoxesProgrammingLanguages[]" type="checkbox" id="checkBoxesProgrammingLanguages[]" value="7" />

C#</label></td>

<td>&nbsp;</td>

<td><label>

<input name="checkBoxesProgrammingLanguages[]" type="checkbox" id="checkBoxesProgrammingLanguages[]" value="8" />

Ruby</label></td>

<td>&nbsp;</td>

<td>&nbsp;</td>

</tr>

<tr>

<td colspan="2" align="left" id="display_status">&nbsp;</td>

<td align="left"><label></label></td>

<td colspan="2" align="center">&nbsp;</td>

<td align="center">&nbsp;</td>

<td>&nbsp;</td>

<td>&nbsp;</td>

</tr>

<tr>

<td colspan="5" align="left" id="display_status">Check/Uncheck using checkbox </td>

<td>&nbsp;<input name="checkAll" type="checkbox" id="checkAll" value="1" onclick="javascript:checkThemAll(this);" />

Check All </td>

<td>&nbsp;</td>

<td>&nbsp;</td>

</tr></table></form>

</body>

</html>

 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript
©-Copyright By Duminda Chamara
JavaScript Validation