function help php

Associate
Joined
19 Jul 2006
Posts
1,847
PHP:
// at the top of the page
function checknumber (){
$number=$_POST['number'];
$number= ereg_replace("[^0-9]","",$number);
$length= strlen($number);
$flag = true;
 if ($length==10)
{
 $flag= true;
 return $flag;
 }
 else {
 $flag=false;
 return $flag;
 }
  }
This logic works.

in main part of page i do
PHP:
<div id="mainblock">
<?php 
checknumber ();
if ($flag==true){
echo"	value is true do something";
 }
else{
echo" value is false	do something else";
}?>   
</div>
but it echo's valuse is false do something else even if the length does equal 10

what am i doing wrong now?

TIA
 
You're not storing the value returned from checknumber, just calling the function, you need...

PHP:
<div id="mainblock">
<?php 
$flag = checknumber();
if ($flag == true) {
   echo "value is true do something";
}
else {
   echo "value is false do something else";
}
?>   
</div>
or easier...

PHP:
<div id="mainblock">
<?php 
if (checknumber()) {
   echo "value is true do something";
}
else {
   echo "value is false do something else";
}
?>   
</div>
Also, not required, but just some info in case you didn't know, in your function I'd check if $_POST['number'] is set, otherwise PHP will display an E_NOTICE; eg.

PHP:
<?php
function checknumber() {
  if (!empty($_POST['number'])) {
    $number = ereg_replace("[^0-9]","", $_POST['number']);
    return (bool) (strlen($number) == 10);
  }
  return false;
}
?>
 
Last edited:
Thanks PaulM

functions look really good and useful and i dont think im using them to there full use.

I seam to write them and then not get the output i want and end up writing more lines of code rather than your simple
if (checknumber())
solution
 
Thanks PaulM

functions look really good and useful and i dont think im using them to there full use.

I seam to write them and then not get the output i want and end up writing more lines of code rather than your simple
if (checknumber())
solution

I think you can even repolace the lines:

PHP:
$flag= true; 
 return $flag;

with:

PHP:
return true

and the same for when flag is false.
 
Also as already said, pass it a parameter instead of hardwiring it to use a POST variable. Then it becomes reusable and not locked down to that particular variable.
 
Back
Top Bottom