Functions, slightly confused to how some use them

Thanks Lesley, appreciate your effort.

Everything you explained has been very helpful but I think you may not have read the previous posts properly as to what Im stuck on.

Originally Posted by Ethan-27 View Post
It also shows how the user can affect the result returned

What I meant to say here is it shows how the users input affect which return is used. This to me makes sense.

Regarding the addthese function that comparison was the one I was most proud of. Funnily enough that is the function I understand most. :slight_smile:

The part about ‘challenge’, I think I understand…(: As explained previously that when echoing just a string, in some cases there is no need to return anything because nothing is really going on (compared to functions that return something) It’s kinda like “here it is, dont complicate, nothing in the way, just echo the bloody thing”

Its quite obvious my bit of fun confused and I apologise for busying your brain more than needs be ,so Ill try to refrain from that in the future and stick to the php vocab. But believe it or not I am so much more clear now, perhaps not totally correct but alot more clear.

I think Im gonna really study some codes this wknd and watch how people use functions in different situations, Im sure itll click soon.

That’s a good idea. And you know what would be even better? Write some code yourself, use them functions. And see if you can get it to work. And do post your code here so we can check if you’re on the right track :slight_smile:

Cheers guido.

I think Ive been doing a bit too much thinking, perhaps some hands on practical is what is needed.

Once again guys thanks for all your help, but most of all your patience :slight_smile:

Yeah, it’s always helpful to experiment.

When I was more of a beginner I used to write little programs all the time, just to see if I could. If I couldn’t, I’d figure out how to do it until I was able to write it. It’s the best way to learn this stuff.

Yeh this is a good idea. I’m trying to write a working blog and I know this is a bit of a stretch at the moment but writing it function by function line by line will probably be quite a good learning experience.

I know it may look like I don’t understand the basics but I think have a grip on things more than it seems… actually no I don’t have a clue :slight_smile:

Perhaps these examples can help understand return and true/false statements

<?php

// Return & Echo
	function rtnMyStr( $str ) {
		return $str;
	}
		echo rtnMyStr('Hello World<br />');

	function echoMyStr( $str ) {
		echo $str;
	}
		echoMyStr('Hello World<br />');
	
// Return within a function	
	function numTest( $num = null ) {
		if( is_null($num) ) return;	
		if( !is_int($num) ) {
			return false;
		}
		return true;
	}	

	// Function return is identical to boolean false
		if( numTest('Five') === FALSE ){
			echo 'numTest(\\'Five\\') is False<br />';
		}
	// Function return is true
		if( numTest(123) ) {
			echo 'numTest(123) is True<br />';
		}

	// Empty argument... function returns nothing
	// Nothing gets echo'd
		if( numTest() ) {
			echo 'numTest() is True<br />';
		}
		if( numTest() === FALSE ) {
			echo 'numTest() is False<br />';
		}
		
			
	function checkArray( $arr ) {
		$isarray = False;
		if( is_array($arr) ) {
			$isarray = TRUE;
		}
		return $isarray;
	}	
	
	$a = array(
		'a' => array(),
		'b' => 'str',
		'c' => array(1,2,3)
	);
	foreach( $a as $k => $v ) {
		$bool = checkArray($v) === TRUE
			? 'True'
			: 'False';
			
		echo 'Key '.$k.' is '.$bool.'<br>';
	}
		

?>

I’m desperately trying to think of what to say here. … Data In - Process - Data out …
That is what programming is fundamentally about. It doesn’t matter if it’s procedural , object oriented or functional programming you get some data in from somewhere, process it, and put it back out somehow

A function is a unit of code that performs a task of some finite unambiguous description, it can be called one or more times by other code.

A function can be thought of as a mini-program. It takes data in, processes it, and returns data somehow - whether through return values or passing parameters by reference.

The addThese function is a very basic function. It takes three values, (data input), adds them up (processes the data) and then returns the processed data (data output).

I’m glad to hear you feel you at least understand it.

… Depends what environment you are working in … echo doesn’t return any value to indicate success or failure of echoing the message to a given output device and print, in PHP, always returns 1.

The language you are using, PHP, doesn’t allow you to go any further in checking the print/echo actually worked.

FWIW the displayError function accepts data, processes it (via the echo call) but doesn’t return anything; the processing provides some data output but in a non-interesting way for the computer doing the processing.

I felt there was absolutely no way for a native English speaker to work out if you had understood anything at all. I have no idea what it would have been like for someone whose first language is not English. I am glad you can comprehend the humour gets in the way of clarity.

Like others have said, studying is good, writing your own code is even better. Try and find a good book or website that teaches programming fundamentals along with PHP. Many books that teach programming fundamentals have exercises at the end of each chapter. The exercises are good to work on to confirm your level of understanding. I’m sure there are some good PHP sites out there that work similarly.

Good luck with your study.

I never had any problems grasping functions when I was learning code. I mainly had trouble with statements; do I have to assign everything to a variable? is it legal to just put a number or a string on a line by itself, if so, does anything happen?

Ethan-27, I’d say in your case understanding functions probably isn’t the root problem here, it’s likely a symptom of a scewed perspective of programming. Just my two worthless cents.

OK…
Hopefully this will answer your question. When scripting or coding, A function function to avoid repetition. A function can be use one time, an infinite number of times or not at all. Coders use the term “calling” when they use a function.

foo($arg){
if ($arg==0){ return;}
if ($arg==1){ return false;}
$modArg=$arg *2;
return “$modArg is 2x $arg”;
}

$a= foo(0);// null
$a =foo(1);// Boolean false
$a=foo(5);// string “10 is 2x 5”

  1. I can call foo(); as many times as needed.
  2. you will notice I used return 3times in the function. In a function the return statement ESCAPES the function and goes back to executing the code where it was called from.
  3. A “return” by itself does not pass any variable back…$a= foo(0);// null.

“thats useless”, you might say… but remember the function of a function is to keep you from having to type the same code over and over … So that means you may have OUTPUT FUNCTIONS… that is functions you use merely to calculate something then ECHO it.

foo($content $headline, $tag=1){
echo “<div class=‘part’><h$tag> $headline</h$tag>$content</div>”;
return;
}

you dont really want to send anything back to the main code you just want a variable output…in that example the return is merely a formality.

when you want something sent back… you use: return $functionvar;
$functionvar has to be a variable that inside the function. This is for the same reason that if you try to work with a variable from your main code within the function, without having passed it TO the function, by putting it in ()… you will get a variable not declared error. This is know as scope…

Ok so you sent a vaiable ( actually a copy of a variable) into the function… but you want to get data BACK out… you can send ONE result out of the function. Thats teh other thing return does it sends a variable or constant out…

return $var; // returns $var to the main code…
return 15; // returns 15 to the main code…
return true; // returns boolean true to the main code…

if you don’t have anything to cat the returned result it is lost. No biggie.
foo(2); // returned value is lost…
$a=foo(2); // whatever foo calculated is stored in $a

why not capture values all the time, you say? well thin about it a function can be ANYTHING… its just to keep you from typic code over and over…

so what if you wanted to check that the result of a value plugged into a formula is not 10, for example…

foo($agr){
$mathStuff=$arg/(2*11);
if ($mathStuff!=10) {return true);}
return false;}

if you follow the code… you will see that foo() will return Boolean true for any value that, when divided by 22 doesnt equal 10… and return Boolean false for anything else

you can use this directly in an if statement in the main code:
if (foo($argToTest)){ do something…}

see, a value you didnt need to capture and a use for returning booleans !

hope that makes things a little clearer

Once again thankyou.

I’ve been reading all your examples and all your advice and feel very lucky that so may people have put such an effort into helping me get past this. It really is appreciated.

I’ve been working on code all day and am starting to write some small working functions. I’ll post them up later this week to see if they are ok.

Something totally off topic occured to me today, I was just wondering, do functions, if, else statements etc mean the same thing in all programming languages…? Perhaps the syntax is different and some parts might not work the same as with others but is their general nature the same …?

Anyways cheer again guys

Could I suggest another way to think about functions.

Suppose you have a complex calculation which you will carry out in several different parts of your site / application / whatever. You would write a function to carry out this calculation and return the value to some variable, which you will then use in some other part of your scripts. You might wish to do this on several different pages.

Perhaps it was the distance in feet between two places give their latitude and longitude.

So you just call the function whenever you need to do this calculation on a particular page, pass the values to work with to the function, and out comes the answer.

You wouldn’t know the answer until you passed the values to the function.

The examples given to help you are usually a bit simple so you can see what is happening. But writing 10 or 20 lines of a calculation once is much better than having to copy and paste these lines, then fiddle with them to put the values you want used in the right place.

But suppose you only needed to do this calculation once on your entire web site or application - why bother to write a function, just do the calculation in normal procedural code.

Hey again guys, been reading up and today Ive written two functions that are really simple and both work.


function basic_prg (&$sum){ 

$sum = $sum *10;

}

$number1 = 15;

basic_prg($number1);

echo "$number1  <br/>"; 


function adding(){
	
global $moves;

$moves = $moves * 10;

}
$moves = 15;
adding();
echo "$moves <br/>";


As you can see they both do the same thing (equal 150) just one using local and one using global scope.

This next function I have written is trying to grab the returned result of the second function (adding) and echo a string back if it is an integer and is not empty. The $moves variable is global.


function check_rtn ($moves);

if (is_int($moves)) && ($moves !=' '){
return true;
}
echo "Yes yes it's a number and you caught it!";

I haven’t actually referenced the function (adding), only the global variable used in it’s code, I’m sure this is part of where Im going wrong.

There are a few errors in the last function:

  1. The function needs an opening and closing bracket, not the semi-colon that is present.
  2. This line:
if (is_int($moves)) && ($moves !=' '){

Should be:

if( is_int($moves) && $moves !=' ' ){

Also, i am thinking there may be a logic error here too. You probably want to check if $moves is empty before you do the addition, not afterwards, because it was always evaluate to an integer (ie nothing * anyNumber = 0). At that point, you would just need an is_int check:


if( is_int($moves) ) {
	echo "Yes yes it's a number and you caught it!"; 
}

Cheers for clearing that code up, it still not showing the string though.

I noticed you didn’t include the return statement , I tried it with and without, still no luck.

So for the function to recognise that the previous function returned a result (hence displaying the echo) I dont need to reference the function (adding)…? Is that because the variable I am using is global…?

you have to pass the variables to each other… or sues them in some way. Right now your code has all of the functions being unrelated to each other! BTW, globalizing variables… is kinda heavy handed.


// stick all the function together in the code, doesnt change the way they work but it's easier to read///

function=basic_prg (&$sum){ 
$sum = $sum*10;
return $sum; 
}

function adding(){
global $moves;
$moves  = $moves *10;
}

function check_rtn($moves){
if (is_int($moves)) && ($moves!=' '){return true;}
return false;
}


$number1 = 15;
echo basic_prg($number1)."<br/>";


$moves = 15;
adding();
echo "$moves <br/>"; 

if check_rtn ($moves){ echo "Yes yes it's a number and you caught it!"; }// calls the function and acts according to the RETURNED result


Thanks for writing that mate. :slight_smile:

Little bit confused though why the string could not just be echoed after the code of that function rather than writing another “if” statement… is there not a way to do that…?

May I also ask why you returned both ‘true’ and ‘false’ in the 3rd function…?

Yes, echo the string in the function, without returning TRUE or FALSE.
If however your funtion returns TRUE or FALSE, and you want to echo the string only when the function returns TRUE, you’ll have to tell that to the PHP parser. Otherwise, how would he know? Guess? :wink:

You are missing a closing bracket, you close the if, but not the function.

Anyway, once resolved that error, I predict that you’ll still not see that string :slight_smile:

And please, to understand the way functions work, put them all on top of your script like dresden_phoenix has done in his post, and leave only the function calls where they are right now (that is: at the point in the script where you need to call them).

Cheers that worked :-). I can now see the echo!!!
I’ll also follow the instruction of putting the functions at the top now

The example given by phoenix (thankyou) I can’t get to work though. I just keeps getting syntax errors that I can’t see…?

What happened to your post though? Did you delete it?

The example given by phoenix (thankyou) I can’t get to work though. I just keeps getting syntax errors that I can’t see…?

You can’t see? Then how do you know they’re syntax errors?