0

I am trying to add up the character length from an inserted URL. I have grabbed all the selected URLs from the database in an array and am trying to add them up in a foreach function.

function countLen($email) {

    $countLen = mysql_query("SELECT url FROM urls WHERE user='$email'");
    $resultLen = mysql_result($countLen, 0);

    foreach($resultLen as &$string) {


        $length = strlen($string);
        $totallen = ($totallen + $length);

        return $totallen;




    }





}
2
  • 2
    You appear to be returning from inside the foreach. Did you mean to do that? Commented Jan 12, 2012 at 21:29
  • 1
    You need to move your return statement outside of the foreach loop. Commented Jan 12, 2012 at 21:31

3 Answers 3

6

You could just do it all the summing in SQL:

function countLen($email)
{
    $res = mysql_query("SELECT SUM(LENGTH(url)) as 'sum' FROM urls WHERE user='$email'");
    return current(mysql_fetch_array($res));
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try:

$total = 0;

$res = mysql_query("SELECT url FROM urls WHERE user='$email'");
while( $row = mysql_fetch_assoc($res) )
{
  $total += strlen( $row['url'] );
}

Comments

1

The return should be out side the loop.. like

function countLen($email) {

  $countLen = mysql_query("SELECT url FROM urls WHERE user='$email'");
  $resultLen = mysql_result($countLen, 0);
  $totallen = 0;
  foreach($resultLen as &$string) {
    $length = strlen($string);
    $totallen = ($length + $totallen);
  }
  return $totallen;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.