Jump to content

Need Help with using rand() with an array()


nems

Recommended Posts

Before I begin I just want to say i'am brand new to php, and unfortuantly not a quick study either :(. Anyway I was assigned the assignment below and have spent about an hour and half on it, and havn't gotten very far, well no where to be exact. So I was hoping I could get some help with this.

 

1. Create a file called Lesson2.php. This will be the main file where the main function calls will reside.

 

2. Create a second file named Lesson2.inc.php. This is where all functions will reside.

 

3. Require Lesson2.inc.php in your Lesson2.php file.

 

4. Write a function that will accept an array by reference (&) and fill the contents of the array with random data using the “rand” function and add the letter “A” to the output. Create 10 array elements this way using a loop of your choice.

 

5. Create a second function that will accept an array by reference and an index value. Call the function and pass in the original array and choose an index value between 1 and 10. Change the value at that index to be a new array. (Array now becomes multidimensional)

 

6. Add an element to the same index value as above and a key value of Name and Email and enter some data accordingly. The output should look similar to this:

 

Array

(

    [0] => A2420

    [1] => A1084

    [2] => A2154

    [3] => A384

    [4] => A2960

    [5] => Array

        (

            [Name] => Eric Gen

            => name@email.com

        )

 

    [6] => A2545

    [7] => A2519

    [8] => A1368

    [9] => A1937

    [10] => A764

)

 

7. Create a function will emulate the print_r function in PHP. The print_r function raverses the entire array and outputs the value of every element in that array as shown above. The function must be recursive and output should be similar to the result above. Use a for loop to traverse the array.

 

I get stuck on step 4, and so if someone could lead me in the right direction that would be great.

Link to comment
Share on other sites

You may be new to technical forums in general so you may be unaware that we will not provide solutions to your homework problems.  So tread carefully in how you ask for help with this type of stuff.

 

That said, you're not asking for a solution.  You're asking for general help with step 4.

 

My question to you is, exactly what part of step 4 is confusing you?

 

Have your written any code for step 4 yet?  Can we see it?

 

Step 4 requires that you write a function.  Do you know how to write functions?

 

It also requires your function to accept an argument.  Do you know how to do that?

 

The argument must be passed by reference.  Do you know how to do that?  (Kind of odd your teacher would want it by reference since PHP5 will pass arrays by reference anyways; or at least that was my understanding.)

 

You will need to write a loop that executes 10 times.  Do you know how to do that?

 

You get the idea.

Link to comment
Share on other sites

Yes, your right i'am new to technical forums. I should have been more clear in my first post, iam not so much looking for the solution as just for some guidance on how to go about it. Anyway as far as what im looking for in step four is how would i fill an array win random integers.

 

Im thinking its something like:

 

function array()
{
$counter = 0;
$arr = array("A"rand(100,1000));

while ($counter => 10)
{
echo $arr;
$counter++;
}

}
echo array;

 

I'am aware that isn't all the steps for what the question is asking but that is what i would like to figure out, then manage the rest on my own.

Link to comment
Share on other sites

You can not name your function array because array is a reserved word for the language.

 

As far as the functions are concerned:

http://www.php.net/manual/en/functions.user-defined.php

http://www.php.net/manual/en/functions.arguments.php

 

As far as the loop syntax is concerned:

http://www.php.net/manual/en/control-structures.while.php

http://www.php.net/manual/en/control-structures.do.while.php

http://www.php.net/manual/en/control-structures.for.php

According to your assignment, you can pick any of the three types of loop for your function.

 

More help with arrays:

http://www.php.net/manual/en/language.types.array.php

 

When programming, you should follow a divide and conquer mentality.

 

So let's divide your problem.

 

Step 1)  Write a loop that iterates 10 times.

 

Step 2) Write a small program that creates an array and assigns elements to it.

 

Step 3) Now combine #1 and #2 by writing a program that creates an array and uses a loop to assign 10 things to it.

 

Try that and see how far you get.

Link to comment
Share on other sites

Thanks, those references helped alot. Alright so this is what I have so far.

 

<?php
$arr = array();

function array1(&$arr)
{
for ($i = 0; $i < 10; $i++) 
{
$arr[$i] = rand(100,1000);
}
}

function array2(&$arr)
{
unset($arr[5]);
$arr[5] = array("Name" => "Jarrod Wright", "Email" => "jarrodwright@live.ca");
}

function display
{

}
?>

 

So now what I'm trying to do is with function display, emulate the  print_r function. What I don't understand is how I'm suppose to echo out the $arr reference when it doesn't save the values i set in functions "array1" and "array2". At least that's my understanding of how references work.

 

So is there a way to save the values from the function to the reference is I guess what I'm asking. Oh and any tips on naming conventions for functions, for some reason I have a feeling naming them "array1" and "array2" is a bad idea.

Link to comment
Share on other sites

Alright I tried looking for the modify post button but I couldn't locate it. :S So pardon the double post. Anyway I figured the solution for what I asked in my last post and that was to put the reference in the .php file and not the .inc.php file. So now what I'm trying to figure out is how to emulate the print_r in my display function. I'm thinking i'll need a for loop to go through the elements of the array, but with some sort of check for array since element 5 is an array.

 

Can someone point me in the right direction.

Link to comment
Share on other sites

Alright, so I answered my own question and got a working model of what I wanted to do which you can see below.

 

<?php
function array1(&$arr)
{
for ($i = 0; $i < 11; $i++) 
{
$arr[$i] = 'A' . rand(100,1000);
}
}

function array2(&$arr)
{
$arr[5] = array("Name" => "Jarrod Wright", "Email" => "JarrodWright@Live.ca");
}

function display(&$arr)
{
for ($i = 0; $i < 11; $i++)
{
	if ($i != 5)
	{
	echo "[$i] => ", $arr[$i], "</br>";
	}

	else
	{
	echo "[$i] => ", $arr[5], "</br>";
	echo str_repeat(" ", 10),"( </br>";
	echo str_repeat(" ", 20), "[Name] => ", $arr[5]["Name"], "</br>";
	echo str_repeat(" ", 20), "[Email] => ", $arr[5]["Email"], "</br>";
	echo str_repeat(" ", 10),") </br></br>";
	}
}
}
?>

 

Now just out of curiosity is there a better way to do this? For example i really wanted to use a "/t" instead of  str_repeat but I couldn't get it to work. Also my for loop only spits out the name and email because I set it to the exact number to do so, is there a way to check it so it knows when the array pops up instead of just checking for the element number I assigned it to?

Link to comment
Share on other sites

This is the assignment:

5. Create a second function that will accept an array by reference and an index value. Call the function and pass in the original array and choose an index value between 1 and 10. Change the value at that index to be a new array. (Array now becomes multidimensional)

 

This is your function:

function array2(&$arr) {

 

You're supposed to accept a second argument and use that to choose which index to set.

function array2( &$arr, $index ) {
  // TODO fill in function body
  }

 

7. Create a function will emulate the print_r function in PHP. The print_r function raverses the entire array and outputs the value of every element in that array as shown above. The function must be recursive and output should be similar to the result above. Use a for loop to traverse the array.

http://php.net/manual/en/function.is-array.php

http://www.php.net/manual/en/function.is-scalar.php

http://www.php.net/manual/en/control-structures.foreach.php  (Take special note of the $k => $v syntax)

 

Your display() function should be recursive.  A recursive function is one that calls itself and stops calling itself when certain conditions are met.  For better explanation and examples see:

http://en.wikipedia.org/wiki/Recursion_(computer_science)

 

For example i really wanted to use a "/t" instead of  str_repeat but I couldn't get it to work.

http://www.php.net/manual/en/language.types.string.php

 

Take special note of escape sequences.  They start with a backslash, not a forward slash:  "\t" is a tab.

 

Based on your output, you are displaying this in a browser.  Browsers ignore extra white space.  You can have 30 spaces, newlines, and / or tabs in a row and the browser will display one space.  You can get around this in at least two ways:

1) Output your code between pre tags: http://www.w3schools.com/TAGS/tag_pre.asp

(As an aside, w3schools is an excellent XHTLM reference)

 

2) Change the content-type of the document to text-plain.  To do this, make this the first two lines of your PHP program:

<?php
header( 'Content-Type: text/plain' );
// program follows...
?>

(Strictly speaking it doesnt have to be at the very beginning of your program, but if you (based on your experience) do not put it there, you will encounter mysterious errors.)

 

You also asked about naming conventions for your functions.  Your instinct is correct, array1 and array2 are terrible function names.  Names should describe what the function does or what the variable represents.  Better names would be:

array_fill()

array_set()

 

However, array_fill() is already a built-in function, so you'll have to use another name:

array_populate()

array_set

 

Another common practice for assignments or very small programs such as this is to prefix names with something like my_:

my_array_populate()

my_array_set()

 

:)

Link to comment
Share on other sites

Thank you for replying, and sorry I didn't get back to you sooner. So I have worked on my previous code and made some changes after reading your last reply.

 

First I have changed my function names to; my_array_populate, my_array_set, and my_display. So my code should be easier to read and understand now.

 

Second in my function array2 which is now my_array_set I have used a reference of $index and made an if else statement that only executes the set as long as $index <= 10, this wasn't requested in the assignment but I started to enjoy myself and got kind of side tracked.

 

Third I took special note of the $k and $v syntax and changed them to $key and $value. Also I incorporated the "is_scalar", which I must thank you for cause I thought that was pretty niffy. I read through the article on recursion and I understand how it works, however I could not wrap my head around how to apply it to this code.

 

Lastly i tried to apply the "\t" escape sequence to the code in replace of the "str_repeat" that I was using before and found that only the first instance of "\t" worked and the rest were ignored. I tried working around this by using "\n" hoping that it would jump to a new line where i could use "\t" again but that wasn't the case. So I removed the "str_repeat" and "\t" all together.

 

So this is my final code that I have handed in, however I would like to figure out how I would of made this recursive for my own benefit. It just stumped me that the question ask to do a for loop in the function and make it recursive.

 

<?php
function my_array_populate(&$arr)
{
for ($i = 0; $i <= 10; $i++) 
{
$arr[$i] = 'A' . rand();
}
}

function my_array_set(&$arr, &$index)
{	
if ($index <= 10)
{
$arr[$index] = array("Name" => "Jarrod Wright", "Email" => "JarrodWright@Live.ca");
}
else
{
echo "Your data can't be processed. </br>";
}
}

function my_display(&$arr, &$index)
{
if ($index <= 10)
{
	foreach ($arr as $key => $value)
	{
		if (is_scalar($value))
		{
		echo "$key => $value</br>";
		}
		else
		{
		echo "$key => $value </br>";
		echo "( </br>";
			foreach($arr[$index] as $key => $value)
			{
			echo "$key => $value </br>";
			}
		echo ") </br>";
		}
	}
}
else
{
echo "You must enter a number between 0 and 10.";
}
}
?>

 

Oh and sorry if my tabbing of code is awful, I don't really know if their is a preferred method to this or not so I just what is easy for me to read and make sense of, though suggestions are always welcomed.

Link to comment
Share on other sites

Oh and sorry if my tabbing of code is awful, I don't really know if their is a preferred method to this or not so I just what is easy for me to read and make sense of, though suggestions are always welcomed.

http://en.wikipedia.org/wiki/Indent_style

Your style doesn't matter and will evolve over time.  Just read that wiki article and pick one that works for you and then modify as necessary.  If you ever work for a larger company they might dictate a style to you though.  :)

 

Second in my function array2 which is now my_array_set I have used a reference of $index and made an if else statement that only executes the set as long as $index <= 10, this wasn't requested in the assignment but I started to enjoy myself and got kind of side tracked.

Using an if to check that the passed index is within bounds is good.  It means you're thinking about error checking.  However you should be checking that: if( $index >= 0 && $index <= 10 )

Passing index by reference is unnecessary in this case since your function does not modify it; it uses it as "read only."  You only need to pass by reference when your function will change the argument so that the change is seen by the code that called the function.  If this doesn't make sense I can give you some resources to help with that.

 

Your my_array_display() doesn't need an $index argument at all since you can use foreach and won't be using the $index argument for anything.

 

As for your my_display(), here's one with a few pointers:

<?php

$foo = array( 'a', 'b', 'c', array( 'x', 'y', 'z' ), 'l', 'm', 'n' );
echo '<pre>';
my_display( $foo );
echo '</pre>';

function my_display(/*&*/$arr, /*, &$index -- WON'T BE USED, SO NOT NECESSARY*/ $indent = 0 /* AN INDENTATION ARGUMENT */)
// WE CAN PASS THE ARRAY "REGULARLY" SINCE WE ARE NOT MODIFYING IT
// ALSO, AS IT TURNS OUT, IN PHP5 AND GREATER ARRAYS ARE PASSED BY REFERENCE ANYWAYS
{

        $nl = "\n";
        // The function now takes an $indent argument.
        // Uncomment the following line to see how $indent changes depending on the $arr
        // contents.  How might you combine this increasing value to create your indentation?
        //echo "Indent is {$indent}{$nl}"; // <-- UNCOMMENT THIS LINE AND PUT ON THE THINKING CAP
    
//if ($index <= 10)     // NOT NEEDED SINCE WE'RE USING FOREACH,
//{                     // IT WILL GET THE VALID INDEXES FOR US
        if( is_scalar( $arr ) ) {
            // IS THE ARRAY A SCALAR? IF SO JUST PRINT IT
            echo $arr . $nl;
        }else{
	foreach ($arr as $key => $value)
	{
		if (is_scalar($value))
		{
                            // THIS IS A SIMPLE-CASE, NO RECURSION NECESSARY
                            //
                            // WHEN USING VARIABLES IN DOUBLE QUOTED STRING,
                            // I RECOMMEND ENCLOSING THEM IN CURLY BRACKETS
                            // TO AVOID UNEXPECTED RESULTS
                            echo "{$key} => {$value}{$nl}";
		}
		else if( is_array( $value ) )
		{
                            echo "$key => Array ({$nl}";
                            // $value IS AN ARRAY, WHICH IS WHAT my_display()
                            // OPERATES ON.  SO FOR RECURSION, HERE IS OUR
                            // SPECIAL CASE.
                            my_display( $value, $indent + 1 );
                            echo ") {$nl}";
		}else{
                            // THIS IS A SIMPLE-CASE, NO RECURSION NECESSARY
                            //
                            echo "{$key} is not an array or scalar!{$nl}";
                        }
	}
        }
        // NEXT LINES ARE ATTACHED TO THE COMMENTED-OUT IF ABOVE, SO WILL
        // BE UNNECESSARY AS WELL
//}
//else
//{
//echo "You must enter a number between 0 and 10.";
//}
}
?>

 

Link to comment
Share on other sites

As it turned out the tabbing was not needed, though im still going to try and get it going for my own benefit. Anyway I looked at what you had done, tested it out, and I must say you have been awesome with helping me through this. My final code is:

 

<?php
function my_array_populate(&$arr) //Populating array
{
for ($i = 0; $i <= 10; $i++) 
{
$arr[$i] = 'A' . rand();
}
}
function my_array_set(&$arr, $index) //
{	
if ($index >= 0 && $index <= 10 )
{
$arr[$index] = array("Name" => "Jarrod Wright", "Email" => "JarrodWright@Live.ca");
}
else
{
echo "Your data can't be processed. </br>";
}
}
function my_display($arr)
{
$nl = "</br>";

if(is_scalar($arr)) 
{
	echo $arr . $nl;
    }
else
{
	foreach ($arr as $key => $value)
	{
		if (is_scalar($value))
		{
			echo "{$key} => {$value} {$nl}";
		}
		else if(is_array($value))
		{
		     echo "{$key} => Array {$nl} ( {$nl}";
			 my_display($value);
                 echo ") {$nl}";
		}
		else
		{
			echo "{$key} is not an array or scalar!{$nl}";
            }
	}
}
}
?>

 

I can't thank you enough for guiding me through this process. You have solved my questions :)

Link to comment
Share on other sites

I can't thank you enough for guiding me through this process. You have solved my questions

No problem.  As I said before, tech-forum users are very unlikely to solve your homework for you.  But if you present yourself as someone who wants to go through the learning process (as you did yourself), then someone will generally walk you through it.

 

Anyways, I'll throw some more your way.  If you've learned about this in your class already, then feel free to implement it in your program.  If you've not learned about this already, then you may not want to include it as it will be an indicator to your professor you had outside help and we want them to know that even though you had help, you did do the assignment yourself.  (If in doubt, I guess you could give them the URL to this thread.)

 

Notice how you've hard-coded 10 as the upper limit on your array?  If you later decide you want it to be 20, 5, or 1000, then you'll need to edit your code in two places.  Your program is small and two edits are not a big deal.  But imagine your program were much larger.  The common example is you are writing a large math program and have coded 3.14 in thousands of places.  Then you decide it should be more precise and want to use 3.14159.  Well now you have thousands of edits to make!

 

Luckily we have the concept of constants to help with such problems:

http://php.net/manual/en/function.define.php

 

Link to comment
Share on other sites

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.