Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    PHP


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Random Item Of An Array


What is the best way of picking out a random item of an array, regarding speed and CPU-usage ? I need a super fast way of picking out an ID from my MySQL db.




View Complete Forum Thread with Replies

Related Forum Messages:
Write A Conditional Statement To See If The Current Item In An Array Is The Last Item.
This seems like it would be so simple, but I haven't been able to solve it. I want to write a conditional statement to see if the current item in an array is the last item. I tried

if (count($array) == (current($array))

but that didn't work. count($array) will give me the number of items in the array. What do I use for the current position in the array.

View Replies !
Array_unique - How-to Get First Item Value In Repeated Array Item
I would like to know how-to get the first value of repeated items too in an array using something like array_unique. Code:

View Replies !
Choose Random Item From List But With Different Weighting
I want to choose an item at random, but have different probabilities for each item. One easy way is just to create an array like

$a[]=1
$a[]=2
$a[]=3
$a[]=3

That way a random number between 1 and 4 would give the weighting I want, but it seems like there has to be a much smarter way to do this. I've seen some algorithms for random distributions, but they don't quite do what I want. Oh yeah - must not require a DB; this should work with values from a CSV or similar ...

View Replies !
Array Explode Problem Result In A 6 Item Array
I have the following:

$BB_Basket = "basket=¦APL6007,2.00¦AVX8900,1.00¦ARCAV500,1.00";
$basket_containers = explode('¦', $BB_Basket);
unset($basket_containers[0]);
print_r($basket_containers);

This results in

Array ( [1] => APL6007,2.00 [2] => AVX8900,1.00 [3] => ARCAV500,1.00 )

Now when I try to explode further with

$basket_items = explode(',', $basket_containers);
print_r($basket_items);

This results in

Array ( [0] => Array )

This should result in a 6 item array. Any ideas what I'm doing wrong?

View Replies !
Item In Array
I have an array, set up like this:

$this->navigation_array['Home'] = array('text' => 'Home', 'act' => 'Home', 'redirect' => 'No', 'active' => 'Home', 'link' => 'index.php?act=home', 'default' => 'Info');
$this->navigation_array['Forums'] = array('text' => 'Forums', 'act' => 'Forums', 'redirect' => 'No', 'active' => 'Forums', 'link' => 'index.php?act=forums', 'default' => 'Info');
$this->navigation_array['Users'] = array('text' => 'Users', 'act' => 'Users', 'redirect' => 'No', 'active' => 'Users', 'link' => 'index.php?act=users');
$this->navigation_array['Config'] = array('text' => 'Configuration', 'act' => 'Config', 'redirect' => 'No', 'active' => 'Config', 'link' => 'index.php?act=config');

I want to find the first item inserted into the array, namely "Home". What is the fastest way to just call the first entry? You cant use $this->navigation_array[0] in this case because the keys are text not numbers.

View Replies !
Deleting An Array Item
I have a standard array:
$foo = array(
0 => 'abc'
1 => 'def'
2 => 'ghi');

and I have a variable, $bar, which equals 'def' ... and I want to check
my array to see if the value of $bar exists in the array, and if it
does, delete it from the array.

if (in_array($bar, $foo)) {
// what goes here???
}

I've done this before, but for the life of me, I'm drawing a blank now.
Help a bruthah out?

View Replies !
Delete Item From Array
How do I search for an item within an array, then delete it?

View Replies !
Remove An Item From And Array Entirely
How do you remove an item from an array...

View Replies !
Remove Item From Array
I'm having some trouble understanding how to remove items from an array. The array is created like this: Code:

View Replies !
Modify Array Item
I'm building a shopping cart and need to add the function so if an item is selected twice, the 'quantity' counter increments. I can't get the syntax right for modifying the array value. I have this:

foreach ($_SESSION['basket'] as $key => $row)
{
if ( $row['gnsz']==$gnsz)
{
$newqty=$row['qty'] ;
$newqty++;
$row['qty']= $newqty;
}
}

it picks up the first qty value but I can't seem to modify it in the array. I'm making a dumb mistake somewhere .

View Replies !
Put The Itemid Of An Item Into An Array.
$count = 1;
foreach($trade as $val) {
$val = checkinput($val);
$sel=mysql_query("SELECT * FROM `inventory` WHERE `ID` = '$val' AND `userid` = '$userid2'") or die(mysql_error());
$n=mysql_num_rows($sel);
if($n == 0) {
$input = "You do not own this item.";
error($input);
}
$g=mysql_fetch_array($sel);
$itemid = $g['itemid'];
$itemid[$count] = $itemid;
$count++;

}

Basically, my script is trying to put the itemid of an item into an array. The problem i'm getting is that, it's not saving the values in the array. For example, if i have 3 items and it puts them into the array, it will only save the 3rd item in the array $itemid[3] and 1 and 2 will be blank.

View Replies !
Current Item From An Array
i have an include file with many arrays that look like this: Code:

$event[] = array ('stuff' => 'bla');
$times[] = mktime(0,0,0,6,9,2007);

as of right now, I am using asort to sort all of these by date and display them as a list.

View Replies !
Find Item In Array
I have the following array

$array = array('k1' => 'v1','k2' => 'v2','k3' => 'v3','k4' => 'v4');

how do i select the value that is provided BEFORE the key i provide

ex:
$mykey = "k2";
$array = array('k1' => 'v1','k2' => 'v2','k3' => 'v3','k4' => 'v4');
$value = somefunctions(); // gives the value v1

ex:
$mykey = "k4";
$array = array('k1' => 'v1','k2' => 'v2','k3' => 'v3','k4' => 'v4');
$value = somefunctions(); // gives the value v3.

View Replies !
How To Remove An Item From An Array
Been looking around on how to remove an item from an array, i need the item totally removing, without a gab in the array, as i will be using the implode fuction afterwards.

View Replies !
Item In A Multidimensional Array
I have a multidimensional array (I think). It is an array that has arrays inside it. The inside arrays all have the same structure, (qty, product, color, size). How do I count how many items are 'White' * qty? I looked into the php manual and found array_count_values but others say it doesn't work with MD arrays.:confused:

array(
[0] array([0]qty, [1]product, [2] color, [3] size)
[1] array([0]qty, [1]product, [2] color, [3] size)
[2] array([0]qty, [1]product, [2] color, [3] size)
[3] array([0]qty, [1]product, [2] color, [3] size)
[4] array([0]qty, [1]product, [2] color, [3] size)
[5] array([0]qty, [1]product, [2] color, [3] size)
[6] array([0]qty, [1]product, [2] color, [3] size)
...)

View Replies !
Extra Item In My Array
Why is my code.

$urlarray = explode("/", "/about/new/index.php");
print_r($urlarray);

returning this

Array ( [0] => [1] => about [2] => new [3] => index.php ).

Perhaps I am being dense but why do I have an extra empty value at the beginning of the array. Is there any way I can make it return the ones I want (ie only those containing an actual value) or do I simply have to work around this.

View Replies !
Delete An Item From An Index Array?
How can I delete an Item from an index array in php4?

View Replies !
Shopping Cart Item Array
Trying to build a small simple shopping cart and I am having difficulty getting the solution. The cart is displaying each product, but it is overwriting the values. So if I have added 10 products, it shows ten items, but each item has the values of the last product I added.

I think that this may be due to me trying to use a key to store both an array and string at once, but Iam not sure. I have looked at other examples but due to different methods, syntax is throwing me off. Code:

View Replies !
Remove A Single Item From An Array
I have gathered an array of ID's. I need to go throught the array and find a specific ID and remove it from the array. Because we want to keep that ID. Any suggestion of how to do that.

View Replies !
Preg_split First Item In Array Is Blank
could someone please explain to my why using the code below generates a blank item in $array[0] please. The 'x' from xbox360 is in $array[1]?

View Replies !
Remove Item From Session Array
i have a simple script that adds an item id to a session Code:

View Replies !
Select One Row Of An Array Where Item Number Is ..?
When I call the Ebays XML API I get an array or something similar back (see the code sample), is it possible to "select item_id where item_id = 123123" or something similar as in MySQL? If, How can I do that? Also, I need to attach a PHP variables to the row I selected as for example $starttime, $endtime and so on.

Here is the code sample (the end of the scritpt);

PHP Code: ....

View Replies !
Retrieving Previous Array Item
I have an array. The array key is the id of the item (for example
categories[91], 91 is the ID of the category) all ID are not exactly in
date order, but they're added to the array in date order, how do I find
the previous (in the sense of when it was added) array entry of, for
example category[ྗ']?

View Replies !
Arrays : Returning A Reference To An Array Item ??
I am currently storing a set of objects inside an array,

$itemlist = array();
$itemlist[] = new item("myitem");
//...

and I am looking to develop a search function, which returns a
reference to the found item.

function &search_item($itemlist,"myitem") {
//...
}

I am trying to figure out how to obtain a reference to a given item in
an array.
Indeed, foreach() and each() seem to work on copies of the data in the
array.
For example:

$array = array("a","b","c","d");
print_r($array);
foreach($array as $v) $v="xxx";
print_r($array); // $array is unchanged

reset($array) ; while(list(,$v)=each($array)) $v="xxx";
print_r($array); // $array is unchanged, again

View Replies !
Deleting A Single Item From The Middle Of An Array?
I have an array that contain objects, I want to be able to test against the id of that object and remove it from the array. In it's simplest for I want to go from this:

$people = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Jo');

...to this...

$people = array('Tom', 'Dick', 'Brenda', 'Jo');

The fact that the items in the array are objects should not matter right? Plus I've already written my loops and conditionals to check which item i need to remove.

function removeItem ( $item ) {
   $len = count ( $_SESSION['basket_arr'] ) ;
   if ( $len == 1 ) {
      emptyBasket ( ) ;
   } else {
      for ( $i = 0 ; $i < $len ; $i++ ) {
         if ( $item->id == $_SESSION['basket_arr'][$i]->id ) {
            //$_SESSION['basket_arr'][$i] must go
         } } }}


View Replies !
Removing Item From Array Then Overwriting File
I have a bookings.txt file which has a list of dates each on a new line, for example: -

21/06/07
22/06/07
29/06/07
25/12/07
01/01/08

I also have a variable $event_dd_mm_yy which I want to remove from this file if found. Code:

View Replies !
Random Array Value
I have done this before but need to generate random values from the array. I can get the key to echo, but not the value. Code:

View Replies !
Random Array
Im trying to make a script that randomly generates 4 numbers from an array, without duplicates. I have the random generation done, but i cant figure out how to get rid of duplicates. Code:

View Replies !
Random Subarray From An Array
First, the code:
---------------------
$maxNo = 500
$numbers = range (1,$maxNo);
srand ((double)microtime()*1000000);
shuffle ($numbers);
$subarray = array_slice ($numbers, 0, 24);
ksort ($subarray); // this also don't work!!!
while (list (, $number) = each ($subarray)) {
echo "$number, ";
}
---------------------

I hoped this piece of code will generate random numbers from 1 to 500
but every time it generates the same sequence. Why?

Also, when I change $maxNo to some other number, it changes the
subarray, but then it stayes the same until I change the $maxNo again.
If I change it back to 500, it's the first sequence all over again.
This is the infamous sequence:
30, 3, 482, 286, 226, 414, 158, 258, 98, 478, 222, 354, 94, 386, 130,
350, 34, 481, 225, 290, 97, 418, 162, 353,

This is definitely not how I understand word "random"!

And one more thing: this example is how this thing works on my home
computer. I have the same application on web server, and it doesn't
work the same way! It changes subarray every time I refresh the page,
but the numbers are inclined to upper limit, so if I put $maxNo = 500,
10 out of 24 numbers will be between 480 and 500. Why they prefer
upper limit?

View Replies !
Problem With Random Array
I am using this code to randomly select one value from an array.

srand ();
$rec = array("1","2","3","4","5","6");
$rec = $rec[rand(0,count($rec))];
print $rec;

problem is, is sometimes it returns nothing. can anyone see how
to make this so it always selects something.

View Replies !
Order My Random Array
Can i select a specific order (not a sort but a particular order) rather than this random order that is generated (and returned by $new_arr) in the code:

View Replies !
Select Random Array Value
I have an array which has $key and $values set. I want to randomly select one of these values. How would I do this?

View Replies !
Random Element From An Array
seems simple enough, but not as much as rand($ARRAY); how would i select a random element from an array?

ie $User_Prize = rand($Users);

View Replies !
Random Pair From An Array
here is my code:

Code:
$query = "SELECT `filename`, `url` FROM (featured_articles) ORDER BY `KEY` ASC LIMIT 5";
$result = @mysql_query($query);

while ($row = mysql_fetch_array
($result, MYSQL_ASSOC)){
printf (" ID: %s FileName: %s", $row['url'], $row["filename"]);
}

echo "Recent featured articles<br /><a href='./articles/?p=$featured_article_url'><img src='./images/featured_articles/$featured_article_img' alt='Featured article'></a>";

the trouble is that if I use array_rand() it returns the array elements in a completely random order. I want to keep element 0 paired with element 1 and 2 with 3 and 4 with 5, etc. So I want a random 'pair' from the array,how might I do this?

View Replies !
Random Selection Array
I am thinking of making an array style thing, but it selects a random number in the array[number]. How can you do this if the script is something like this:

<?php

$random array("one", "two", "three", "four");

?>

View Replies !
Random Array, But Saving Key
ive got an arrey:

$Avail_Questions[].......

and i want to selet a random element, buti want to save the key with it. im using shuffle() and it rnaodmizes the keys and the values....... so how can i save the key? i had trouble with array_rand(), but im happy to go back to it.

View Replies !
Random String From Array
If i wanted to pull a random string from an array, lets say for like a quote of the day

$quotes = array('quote1','quote2','quote3','quote4');

$todays_quote = ?

What function could i use to provide the variable $todays_quote with a quote from our list?

View Replies !
Random Array Not Working.
I'm trying to pull links from a file display on my page bottoms using a PHP script... The problem is the random variable(link url) keeps repeating... Code:

View Replies !
Random Number Excluding Specified Value In Array
the most efficient way to generate a random number
from a range that will not return values specified in an array?

View Replies !
Multiple Random Images From Same Array
I want to display 4 images (but with possibility of more in future) on a page which are randomly selected from a number of possible images. at the moment I have each possible image as a list in an array, and have found it simple enough to generate the 4 images randomly. The problem I am having is that I don't want the same image to appear more than once, and am having trouble doing this.

As I said, I am new to PHP so I have a lot to learn, but I have built a (fairly basic, admitedly) application in AppleScript on a mac, so I am familiar with many of the basic concepts behind programming, and I could do what I want in AppleScript, but am having trouble translating it to PHP, plus it's been a while since I did that anyway. Code:

View Replies !
Select 4 Results At Random From Array
Doing some more user ranking. Basically I am selecting the top 10% of users based on total points (being in the top 10% qualifies you to be featured), then I want to select 4 users at random from the top 10%. I wrote this to select the top 10% of users based on their total number of bricks (ranking points). Requires a join because of my table structure (using both a user and points table). PHP Code:

$query2 = "SELECT COUNT(user_id) FROM users";
$result2 = @mysql_query($query2);
if ($result2) {
$row2 = @mysql_fetch_array($result2, MYSQL_NUM);
$tu = $row2[0];
if ($tu <  100) {
$pool = 10;
} else {
$pool = round($tu * .10);
}
$query4 = "SELECT users.user_id AS user, SUM(bricks.brick_num) AS brick, users.featured AS feature
FROM users, bricks WHERE users.user_id = bricks.user_id AND users.featured = 'N' GROUP BY users.user_id ORDER BY brick DESC LIMIT $pool";
$result4 = @mysql_query($query4);
if ($result4) {
$row4 = @mysql_fetch_array($result4, MYSQL_NUM);

I now want to select 4 results at random from this array and store them in a new array. I know how to use shuffle/rand but how do I limit to 4 results? Should I just randomize and write a loop with a counter and stop at 4?

View Replies !
Random Element From Associative Array
I've got an associative array named $pictures.
I've got there filenames for example: "picabc.jpg"

I want to randomize this array. Hmmm...
Maybe you will see, what I mean on example:

I wanna do something like:

drawOneOfElementsIntoVariable($picture);
echo("<img src="$picture" />");

View Replies !
Random Echo Array Elements
I have something like this: $colors=array("red", "blue"); And I want to randomly echo one of the things in the array. But let's say I want it to be more likely for it to be red than blue. I guess I could put red into the array twice, but is there a quicker way.

View Replies !
Selecting A Random Element From An Array?
something like the following:

while(empty($Var_Name)) { DO STUFF}

the reason is that im selecting a random element from an array and puting it into another rarray, but if it isnt valid or doesnt select the element, then itll repeat.

View Replies !
Array Sorting - Select A Random
If I have an array that has maybe 50 things in it, I want to select a random sample of say 5 things. So I know I can use sort() but I want the results to be completely random and not just the top 5 or something in the middle. Can anyone help me do that?

View Replies !
Select A Random Row From A Column In An MS SQL Table Or From An Array?
Is there a way to either select a random row from a column in an MS SQL table or from an array? If so how would I go about it?

View Replies !
Retrieve Array Subset In Random Order
Anyone have a clever way to retrieve for example, items 0-29 from an
array of size N>29, in random order? The catch is that I dont want to
print any items more than once and I dont want to miss any.

This is for a tag cloud where I have sorted them by popularity but now
I need to display only the top 30. I do this now but they are in
order of popularity and its not really a 'cloud'. If I could retrieve
the top 30 in some random order, it would look better.

View Replies !
Iterator First Item?
Let's say I have the code:

foreach($data as $row)
{
do something with each $row
}

Is there a way to do something specific to the first item iterated?
Pseudocode:

foreach($data as $row)
{
if first time through iteration do something with $row
else do something which each remaining $row
}

Is this possible? I think I could use a regular 'for' loop, using the
length of the $data array as a guide, and then an 'if..else' structure
to see if it is the first time through the 'for' loop, but I was
looking for a more elegant solution.

View Replies !
Get One Row, One Item From Database
I was trying to grab just one row and one field in that row from MySQL, but couldn't find a way other than: PHP Code:

View Replies !
Trying To Split The Item...
I'm trying to make a search thru my mySQL database, so it any keywords are found then I'm adding the details to the next item in an array that I create. I've tested the array and it is storing the information into the array properly because it echoes out all of the information correctly. My problem is that, at the beginning of each item in the array I have information that tells me what part of the database it was pulled from and the id number and also how many times the a keyword was found in that specific database entry. So you have something like this.. Code:

View Replies !
Get Last Item In URL String
I realize how elementary this is, I apologize. Maybe that's why I can't find the right answer. I've tried everything from EXPLODEing the string to SUBSTR_REPLACE.

Can anyone tell me how to just get the last item in a URL string? Like turn this:

/mydirectory/myimg.jpg

into this:

myimg.jpg

View Replies !
Most Recent Item
I have a table with every post in - which has a column for the time the post was created and a column for the thread that this post is located in. My threads table has a column for which forum this thread is in and a column for whether the thread is a sticky or not.

On the forum display page, I'd like to display every thread that is in that forum, but ordering them so that any Sticky threads show first (ordered by date created), and then the non-sticky threads are displayed after those ordered according to the time of the most recent post within that thread.

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved