Search Marketing

   
   

Custom Functions and Array Elements with FOR Loops for Counting

Fri May 02, 2008 10:03 pm
<<     >>
Comments: 0 Views: 221
Integrating PHP custom made functions for use with "FOR" loops.

1. Create a function for adding 5 to any number while counting from 1 - 10.

function Add_Five($num)
{
$x = $num + 5;
return($x);
}

$x = "";

for($i=1;$i<11;$i++)
{
$x .= Add_Five($i)." - ";
}

echo $x;

produces: 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15

You can easily combine many custom functions with loops of all kinds.

2. Add 5, using the function Add_Five(), to an array of numbers.

function Add_Five($num)
{
$x = $num + 5;
return($x);
}

$numbers = array(1,4,22,11,21,34,93);

$count = count($numbers);

$x = "";

for($i=0;$i<$count;$i++)
{
$x .= Add_Five($numbers[$i])." - ";
}

echo $x;

produces: 6 - 9 - 27 - 16 - 26 - 39 - 98

You can see that whatever the array of numbers you start with (which may be unknown), you can interact with that array and put each element of that array through a function.

You first count the number of elements in that array with count(), a built-in PHP function for counting those elements.

Then you can use a FOR loop to interact with each element (number) that exists in that array.



Comments
Name:
*
URL: http: (ex. cnn.com)
Comment:
*
Number:
Math (24 + 5)
* required
SubCategories
Regular Expressions

© 2019 Christonium LLC

Christonium.com
|
Terms of Use
|
Privacy
ccc