Jump to content

Recommended Posts

I figure i should start learning functions. I cant find any tutors for a more complex function im trying to do.

there is a few things that confuses me on how this works.

all these loops I created generate a number that looks like this "4-16-6-29-17-9". which is attached to the variable $address.

what i want to beable to do is grab the "$address" when I call the function. so every time i call the function it generates a new number.

hope someone will help me with this i need to understand this once and for all.

 

function generate() {
$chevron1 = rand(1,39);

$chevron2 = rand(1,39);

$c2 = 0;
while ($c2 < 1) {

if ($chevron2 == $chevron1) {
	$chevron2 = rand(1,39);
	$c2 = 0;
}else{
++$c2;	
}}


$chevron3 = rand(1,39);

$c3 = 0;
while ($c3 < 1) {

if ($chevron3 == $chevron1 || $chevron3 == $chevron2) {
	$chevron3 = rand(1,39);
	$c3 = 0;
}else{
++$c3;	
}}

$chevron4 = rand(1,39);

$c4 = 0;
while ($c4 < 1) {

if ($chevron4 == $chevron1 || $chevron4 == $chevron2 || $chevron4 == $chevron3) {
	$chevron4 = rand(1,39);
	$c4 = 0;
}else{
++$c4;	
}}

$chevron5 = rand(1,39);

$c5 = 0;
while ($c5 < 1) {

if ($chevron5 == $chevron1 || $chevron5 == $chevron2 || $chevron5 == $chevron3 || $chevron5 == $chevron4) {
	$chevron5 = rand(1,39);
	$c5 = 0;
}else{
++$c5;	
}}

$chevron6 = rand(1,39);

$c6 = 0;
while ($c6 < 1) {

if ($chevron6 == $chevron1 || $chevron6 == $chevron2 || $chevron6 == $chevron3 || $chevron6 == $chevron4 || $chevron6 == $chevron5) {
	$chevron6 = rand(1,39);
	$c6 = 0;
}else{
++$c6;	
}}

$address = "$chevron1 - $chevron2 - $chevron3 - $chevron4 - $chevron5 - $chevron6";
}
generate();
echo $address;

Link to comment
https://forums.phpfreaks.com/topic/256981-my-first-function-now-or-never-i-guess/
Share on other sites

Maybe start with something simpler, then when you understand how functions work, build on it from there. With functions, you can either echo directly from within it, or return the value from the function. I never echo directly from within a function. Look this over and see if it makes sense.

 

function DOES_NOT_DO_MUCH() {
     $string = 'This is the lamest function in the world';
     return $string;
}

 

All the above function does is return a fixed string, the value of $string. You can either echo it directly, or assign it to a variable. Both of these will do the same thing.

echo DOES_NOT_DO_MUCH();

$fn_return = DOES_NOT_DO_MUCH();
echo $fn_return;

 

 

Use a different function to accept an argument, use the value of that argument within the function, and return a value.

function DOES_A_LITTLE_MORE($input) {
$string = $input;
$string = strtoupper($string);
return $string;
}

 

Pass a value to a function as an argument via the function's argument list.

 

$lower_case_string = 'this is a string.';
$upper_case_string = DOES_A_LITTLE_MORE($lower_case_string);

echo "Input: $lower_case_string<br>Output: $upper_case_string";

 

The above outputs:

Input: this is a string.

Output: THIS IS A STRING.

In addition to what Pikachu2000 said, you could also look for a tutorial on "variable scope".  This should cover how even though you assigned your final value to $address within your function, it won't be available as $address outside of the function.

 

Variable Scope

nice i got it to work.

one thing though.

im not sure the differance of echoing with in the function or not.

 

what is it consider the way i got it working?

also do i understand this right. i use variables with in the () of  stargate_address_generate(); if i want to run only a certain agrument with in the function? so like if i only wanted to run only one of the loops with in my function but not the rest?

 

 

function generate() {
$chevron1 = rand(1,39);

$chevron2 = rand(1,39);

$c2 = 0;
while ($c2 < 1) {

if ($chevron2 == $chevron1) {
	$chevron2 = rand(1,39);
	$c2 = 0;
}else{
++$c2;	
}}



$chevron3 = rand(1,39);

$c3 = 0;
while ($c3 < 1) {

if ($chevron3 == $chevron1 || $chevron3 == $chevron2) {
	$chevron3 = rand(1,39);
	$c3 = 0;
}else{
++$c3;	
}}

$chevron4 = rand(1,39);

$c4 = 0;
while ($c4 < 1) {

if ($chevron4 == $chevron1 || $chevron4 == $chevron2 || $chevron4 == $chevron3) {
	$chevron4 = rand(1,39);
	$c4 = 0;
}else{
++$c4;	
}}

$chevron5 = rand(1,39);

$c5 = 0;
while ($c5 < 1) {

if ($chevron5 == $chevron1 || $chevron5 == $chevron2 || $chevron5 == $chevron3 || $chevron5 == $chevron4) {
	$chevron5 = rand(1,39);
	$c5 = 0;
}else{
++$c5;	
}}

$chevron6 = rand(1,39);

$c6 = 0;
while ($c6 < 1) {

if ($chevron6 == $chevron1 || $chevron6 == $chevron2 || $chevron6 == $chevron3 || $chevron6 == $chevron4 || $chevron6 == $chevron5) {
	$chevron6 = rand(1,39);
	$c6 = 0;
}else{
++$c6;	
}}

$address = "$chevron1 - $chevron2 - $chevron3 - $chevron4 - $chevron5 - $chevron6";
return $address;
}

$address = generate();

echo $address;

 

 

 

im not sure the differance of echoing with in the function or not.

what is it consider the way i got it working?

 

also do i understand this right. i use variables with in the () of  stargate_address_generate(); if i want to run only a certain agrument with in the function? so like if i only wanted to run only one of the loops with in my function

but not the rest?

 

Echoing from within a function (particularly one that generates a rather random value each time) prevents you from using that result elsewhere.  Imagine you wanted to generate an address for a user and also stash it in a database.  You would call the function and it would be displayed to the user - but how would you capture that value for the database since if you were to call the function again, a different address would be generated.  So sometimes it's better to:

 

<?php

$address = my_function();  # now we have a copy of the result.

save_value_to_database($address);  # save the address to the database
echo $address;  # show the address to the user

?>

 

As for the second part of your question, I have to go so will try answer it later if no one else has.

The variables inside of the () is called arguments.  These will assign the values passed to the function, to these variable names INSIDE the function.

 

<?php

function some_function($var1,$var2) {  //var1 and var2 will be available inside the function, and contain the data passed to the function (you must pass both of these arguments).
  return $var1 . ', ' . $var2;
}

$my_first_name = 'John';
$my_last_name = 'Smith';

$get_name = some_function($my_first_name,$my_last_name);  //pass the variables you desire the function to have, and the function will automatically assign them to $var1 and $var2 inside the function.
$get_name2 = some_function('Have Gun','Will Travel');  //or you can pass it hard coded strings to do the same thing.

echo $get_name . '<br />' . $get_name2;  //echo the function returns will return the strings separated by a comma (what the function returns).

//Passing the same variables (or strings) to this function will return the same thing as the first.  If you omit the second argument (or string), it will only return var1.  This is because we have set a default value to the argument var2, then handled that inside of the function.
function some_other_function($var1,$var2=NULL) {
if($var2 == NULL) {
   return $var1;
}
return $var1 . ', ' . $var2;
}


 

Hope that was simple to follow.

note that it's not only variables that can be passed as arguments, can also pass arrays, objects etc

 

And obviously you don't HAVE to pass a variable, take the following for example...

function some_function($text) {
   return $text;
}

$message = some_function("my random text");
echo $message; // Output: my random text

  • 2 weeks later...

thanks alot guys, came back a few days later to look this all over again. Im starting to make my own functions alot now. Also i just learn the need to use Global now.

 

 

now that im lookig over Jcbones example.

I have a question on whats going on here. so when you call "some_function you are actually making $var1 and $var2 = $my_first_name and $my_last_name ? if so then i notice you are replacing $var1 and $var2 again when you call the function a 2nd time "$get_name2 = some_function('Have Gun','Will Travel');"

 

function some_function($var1,$var2) {

  return $var1 . ', ' . $var2;

}

$my_first_name = 'John';

$my_last_name = 'Smith';

 

$get_name = some_function($my_first_name,$my_last_name); 

$get_name2 = some_function('Have Gun','Will Travel'); 

i just learn the need to use Global now

 

You need to forget that you ever saw any code using the global keyword inside a function definition. It is NOT the proper way of writing general purpose functions.

Variables created inside a function will only ever exist inside that function. Likewise, variables created outside of a function can not exist inside the function. When you call the function multiple times, you are making new instances of it. Nothing is being replaced.

 

Using global will allow you to bypass function variable scope. However, it is very bad practice and should be avoided.

Global = bad, pure and simple.  The whole point behind functions is that they're general purpose, reusable, encapsulated processes that can be used in a variety of contexts.  Global ties code to a particular context, thereby eliminating both reuse and encapsulation.  If you need a parameter from the external scope in your function, pass it through the function's argument list.  That's why it's there.

When you call the function multiple times, you are making new instances of it.

 

Unless you declared the variable static.

 

function foo() {
    static $bar = 1;
    echo $bar++;
}

foo();//1
foo();//2
foo();//3
foo();//4

Here's a shorter version of your function with the same result. $length number of unique values.

 

function stargate_generate_address($length = 7, $possibilities = 36) {
    $chevrons = array_rand(range(1, $possibilities), $length);
    shuffle($chevrons);
    return implode('-', $chevrons);
}

I'm a fan myself ;) Here's an OOP version (with all Stargate "business" logic build in) :D

 

class Stargate {
    public function dial(Stargate_Address $address, Stargate_Energy $energy) {
        try {
            $this->obtainLock($address);
            return $this->generateWormhole($energy);
        } catch (LockFailedException $e) {
            $this->disengageChevrons();
            throw new DialFailedException($e->getMessage(), $e->getCode(), $e);
        } catch (InsufficientEnergyException $e) {
            $this->disengageChevrons();
            throw new DialFailedException($e->getMessage(), $e->getCode(), $e);
        }
    }
    private function obtainLock(Stargate_Adress $address) {
        $pos = 1;
        foreach ($address as $chevron) {
            try {
                $this->engageChevron($pos++, $chevron);
            } catch (ChevronLockFailedException $e) {
                throw new LockFailedException($chevron->toGlyph() . ' could not lock.');
            }
        }
    }
    private function engageChevron(Stargate_Chevron $chevron) {
        // logic here
    }
    private function generateWormhole(Stargate_Energy $energy) {
        // do we have enough energy to create the wormhole?
        // or throw new InsufficientEnergyException();
    }
}

 

try {
    $stargate = new Stargate();
    $wormhole = $stargate->dial(Stargate_Address::generate());
    $wormhole->passThru('something');
} catch (DialFailedException $e) {
    echo $e->getMessage();
}

I think the larger problem is the way im thinking of how to speed my scripts up when accessing the data base.

 

I wanted to use a varaible out side the function so I didnt use more server to add another query in the function.

 

Is there a differance in speed from the two examples below?

 

instead of selecting all 3 at once in one query. Only select 2 things then use another query to select 1 thing? Cause i would perfer to not use variables out side the function at all. I was just concern about to many queries

 

$planets3 = "SELECT siege,name,address FROM planets WHERE name ='".($siege_list)."'";
mysql_query($planets3) or die(mysql_error()); 

 

OR

 

$planets3 = "SELECT siege,name FROM planets WHERE name ='".($siege_list)."'";
mysql_query($planets3) or die(mysql_error());

$planets2 = "SELECT address FROM planets WHERE name ='".($siege_list)."'";
mysql_query($planets2) or die(mysql_error());

 

here is a function i made in question. "the top examples are not related to this function they were just examples"

 

 

Im making a function page that sends diferant types of cell phone alerts to users. The function below is a text message they receive when they first add their number and cell provider. But i need their email address so i need to make a query to grab it. I kept the global thing in here to show what i was trying to do.

Also because im sending a email i dont need to do a return at the end right? Since im not returning anything from the function

 

function cell_alert_signup() {						
	global $cell_number;

$to = $cell_number;
    	$from = "stargate@localhost.com";
    	$subject = "Stargate System Lords";

    			$message = "Alerts are now set up for Stargate System Lords";
   	
mail($to, $subject, $message);   

return $cell_alert_signup;
}

this may help gen you addresses guessing you have given each symble a numerical value

 

function generateUniqueRandoms($min, $max, $count)  
{
	if($count > $max)  
	{  // this prevents an infinite loop
		echo "ERROR: The array count is greater than the random number maximum.<br>\n";
		echo "Therefore, it is impossible to build an array of unique random numbers.<br>\n";
		break;
	}    
	$numArray = array();
	for($i = 0; $i < $count; $i++)
	{        
		$numArray[$i] = mt_rand($min,$max);         // set random number

		for($j = 0; $j < $count; $j++)                 // for each number, check for duplicates
		  if($j != $i)                                 // except for the one you are checking of course
			if($numArray[$i] == $numArray[$j])
			{
				$numArray[$i] = mt_rand(1,39);         // if duplicate, generate new random
				$j = 0;                                // go back through and check new number
			} 
	}
	return $numArray;
}

 

then

$x = generateUniqueRandoms(1, 39, 6);

$r = implode('-',$x);

 

$r would return ex 12-25-16-24-9-6

your 7th is allways your origin :)

omg after reading the guide some more. i see what you guys are saying now finally. I found a example in the manual that clicked with me lol. Now i understand how passing agruments work.

 

to get the most out of my function

 

function cell_alert_signup($cell_number) {						

$to = $cell_number;
    	$from = "stargate@localhost.com";
    	$subject = "Stargate System Lords";

    			$message = "Alerts are now set up for Stargate System Lords";
   	
mail($to, $subject, $message);   

}

 

When I call the function I need to

 

cell_alert_signup($cell_number);

 

but since these is for cell texts and the message is only going to be so long. I should do this instead

 

function cell_alert_signup($cell_number,$message) {

 

$to = $cell_number;

    $from = "stargate@localhost.com";

    $subject = "Stargate System Lords";

 

    $message = $message;

 

mail($to, $subject, $message); 

 

}

 

cell_alert_signup($cell_number,$message); [/code]

 

but since this is just a text message shouldnt I just use only the mail function and not even make a function.

 

 mail($to, $subject, $message);

 

but then again i'll be posting this on several pages and less code on the page is better. Only going ot have 2 types of cell phone alerts anyways besides the sign up one.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.