Page 1 of 1

Functions that return booleans for fun and profit. Rate Topic: -----

#1 hiddenghost  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 39
  • View blog
  • Posts: 621
  • Joined: 15-December 09

Posted 08 April 2012 - 07:31 PM

You should have some intermediate understanding of PHP to follow this tutorial.

I'm going to teach you about functions that return bools.
This tutorial only uses a while loop, but because bools are truth makers they can be used with any logical construct.

Here's the code to copy and run.
<?php


$sentenceApart = array(0, 'You ', 'are ', 'now ', 'checking ', 'for ', 'a ', 'boolean ', 'value ', 'with ', 'a ', 'while ', 'loop. ', '<br>',
            'Using ', 'a ', 'function ', 'you ', 'can ', 'return ', 'a ', 'value ', 'which ', 'represents ', 'truth. ', '<br>',
            'A ', 'return ', 'from ', 'a ', 'function ', 'just ', 'sends ', 'a ', 'value ', 'if ', 'there ', 'is ', 'one. ', '<br>',
            'The is done by writing the return statement like:', 'return $variable;', '<br>',
            'Now ', 'a ', 'logical ', 'check ', 'can ', 'be ', 'done ', 'by ', 'just ', 'calling ', 'the ', 'function. ', '<br>',
            'When ', 'this ', 'array ', 'ends ', 'the ', 'truth ', 'ends, ', 'and ', 'the ', 'loop ', 'ends. ');
            
            
function explainIt($wordsTell)
{
    if($wordsTell){
        return $wordsTell;
    }else{
        return false;
    }
    return;
}
//echo count($sentenceApart);

$makeSentence = "";
while($nowWord = explainIt( next($sentenceApart) ))
{
    $makeSentence .= $nowWord;
}
reset($sentenceApart);
echo $makeSentence;

echo "<h3>More Explanations</h3>";
echo "<p>The echo for the above sentence that comes from the array only executes if the loop ends.</p>";
echo "<p>The next() function advances the array pointer to the next array member on each looping of the while.</p>";
echo "<p>reset() sets the array pointer back to the beginning of the array.</p>";
echo "<p>Because next() chooses the second member of the array on the first looping the first member of the array
is just zero because it's going to be skipped any way.</p>";
echo "<p>Every time explainIt() is called it returns the next value in the array or returns false if the array ends.
This is demonstrated by the line inside explainIt() that reads: \"<b>if(\$wordsTell)</b>\" because the value after the
array ends is null which evaluates to false.</p>";
echo "<p>The power of the function formed as the bool function can be witnessed when you use a function like
mysql_fetch_array() that can be used to get data selected in a query and reassigned to your variables.</p>";
echo "<p>Now that I think of it, it would have been good to use that loop for these paragraphs :)/>";
echo "<h4>You can do all kinds of iterations with this method.</h4>";
echo "<ul>\n
        <li>You can do multiple form verifications.</li>\n
        <li>Use a preg_match() in the if as a short or statement with (square)<b>[]</b> brackets to check for truth.</li>\n
        <li>A do while can also be used like this and is good for running a chain of loops together.</li>\n
        <li>Since code is more encapsulated by using a boolean function it will be more organized.</li>\n
        <li>This encapsulation will also help remove the scary from developing code because it'll be neater.</li>\n
        <li>Assignment in whiles with a function returning boolean helps shorten code.</li>\n
        <li>Once you start to get a feel for this method of coding you'll be thinking of all kinds of ways to use it.</li>\n
      </ul>";

?>



Detailed explanation:
The echo for the sentence that comes from the array only executes if the loop ends.

The next() function advances the array pointer to the next array member on each looping of the while.

reset() sets the array pointer back to the beginning of the array.

Because next() chooses the second member of the array on the first looping the first member of the array is just zero because it's going to be skipped any way.

Every time explainIt() is called it returns the next value in the array or returns false if the array ends. This is demonstrated by the line inside explainIt() that reads: if($wordsTell) because the value after the array ends is null which evaluates to false.

The power of the function formed as the bool function can be witnessed when you use a function like mysql_fetch_array() that can be used to get data selected in a query and reassigned to your variables.

You can do all kinds of iterations with this method.

  • You can do multiple form verifications.
  • Use a preg_match() in the if as a short or statement with (square)[] brackets to check for truth.
  • A do while can also be used like this and is good for running a chain of loops together.
  • Since code is more encapsulated by using a boolean function it will be more organized.
  • This encapsulation will also help remove the scary from developing code because it'll be neater.
  • Assignment in whiles with a function returning boolean helps shorten code.
  • Once you start to get feel for this method you'll be thinking of all kinds of ways to use it.


As an added bonus.
Now for something that has been plaguing the interwebz of help for some time.


while($row = mysql_fetch_array($result)){
    $store['myRow'] = $row['myRow'];
    $store['myOtherRow'] = $row['myRow'];
}




If you've worked with mysql much you've probably used that code.

There is something about fetch_array that makes for sad times for people who are new to using it.

I know I had some of those sad times, and I am guilty of posting to get help for that function when
there are already a ton of help for the question.

Why this? ---> Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given

Since mysql_fetch_array() needs an accurately input parameter every little thing can mess that function up.
It's the difference of resource != false.

Booleans can be used in function parameters as well as returns, but it all depends on your needs.

A way to to help fix the error/warning is to use a die statement after the query function.

$result = mysql_query($query) or die("Error: ".mysql_error());

That will provide you with some information about why the mysql_fetch_array is breaking.
In short the mysql_query function is getting futz up.
Mostly there's a chance that there is a typo, misuse of variables, or code just plain out of order.

You can try PDO too. Look at the php docs for PDO if you haven't yet.
That will help with cleaner and safer queries.

Just had to toot my horn about that because were talking about booleans here.

Some code constructs are just a little strange when we first encounter them.
They can have hidden elements to them that are only revealed through constant use of the programming language.

At least for me any way. I'm quite the bone headed learner, but I make up for it in desire for knowledge and stubborness.

Happy coding and have fun using functions that return bools.

Is This A Good Question/Topic? 0
  • +

Replies To: Functions that return booleans for fun and profit.

#2 Dormilich  Icon User is online

  • 痛覚残留
  • member icon

Reputation: 3486
  • View blog
  • Posts: 10,055
  • Joined: 08-June 10

Posted 22 May 2012 - 03:04 AM

the nitpicker is back ...

some minor point: line #19 is pointless, it will never be reached since every decision in the condition leads to a return. hence you could simplify to:
function explainIt($wordsTell)
{
	if ($wordsTell) {
		return $wordsTell;
	}
	return false;
}

or even
function explainIt($wordsTell)
{
	return (bool) $wordsTell;
}


next thing is about next()/reset(). It would make sense to compare it to PHP’s Iteration Cycle (as employed in the foreach() loop), which works the opposite as described here (see example #2 there). it boils down to:
- reset()
- start loop
* current()/key()
* next()
- end loop

it therefore doesn’t require an empty first item in the array.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1