Where do i put my function to be used in the following loop?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cyandi_man
Forum Newbie
Posts: 12
Joined: Sun Nov 02, 2008 10:47 am

Where do i put my function to be used in the following loop?

Post by cyandi_man »

Where can I stick my function that formats my phone number string from my database
before it is displayed on the page? I am trying to add the following function:

Code: Select all

function format_tel_num($contactNumber){ //<-- contactNumber is a field on database.
return preg_replace('/\d{3}/', '$0.', str_replace('.', null, trim($contactNumber)), 2);
}
$contactNumber = format_tel_num($contactNumber);
Into the following php file below - containing the following code without breaking my loop?
do i need to make this function a global function outside of the loop?

Code: Select all

 
--query that gathers info from database--
$result= mysql_query($query)
 
$nrows=mysql_num_rows($result);
 
if ($nrows == 0) {
echo "There are no clinics listed with that criteria at this time.  Please choose again.";
}
else{
  while ($row = mysql_fetch_array($result)) 
    {
    extract($row);
    if($logos!="../logos/profs/spacer.gif"){
    echo " code that displays data from database";
    }
    else {
    echo " coding that dislpays slightly different data from database";
    }
    }
    }
Thank you guys - you all have been great in answering my questions so far!
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Where do i put my function to be used in the following loop?

Post by s.dot »

try it and see ;)

but i'll be nice and say yes, leave it outside your loop :D
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Where do i put my function to be used in the following loop?

Post by John Cartwright »

You only define the function once, so putting in within the loop won't work. Generally people define all of their functions first in the code.

Then, within the loop, you can repeadidly call the function to display each row properly formatted.
Post Reply