Picking a random string from an array - php

Trying to get this code to work. It might be easier to show what I'm trying to do, and what is missing:
<?php
$array=array(
"something",
"something else"
);
/*pick a random entry in the array and store it as $output*/;
if(strpos($output,"else") !== false){
//do stuff;
}
echo "<div>";
echo $output
echo "</div>"
?>
As you can see, I'm having trouble trying to store a random entry in $output. What I want to do is to pick a random entry from the array, run a strpos on the result to do additional things if the conditions are met, and then output the same random entry between the divs.
EDIT: In case it's not clear, the line commented with /* and */ is supposed to be a 'fill in the blank' line, and not a 'this comment refers to the lines of code below' comment.

Use array_rand() to get a random entry.
$output = $array[array_rand($array)];

Generate a random number between zero and one less than the length of the array, use that as the array index to get a random item from the array.
<?php
$output = $array[rand(0, count($array)-1];

Related

array_intersect and match multiple values same time

In this script, you can see i try validate if 2 values - Jhon 34 -there are in the string called $values the same time, when i send the search i use 2 o 3 words and the idea it´s verification if find exactly this 3 or 2 words, etc, inside array
<?php
$values="Jhon,Smith,252546,34,house,car,phone";
$post="Jhon 34";
$exp_values=explode(",",$values);
$exp_post=explode(" ",$post);
$result=array_intersect($exp_post,$exp_values);
foreach ($result as $results) {
if(count($result)==count($exp_post)) {
echo $results;
print "<br>";
}
}
?>
I use count for show result only if the intersect elements it´s the same number as in the $post, because $post show values i want search inside $values, the result it´s ok if the same words find inside $values
The results it´s wrong because detect one word but i need detect all words i send, if array have all these words result must be ok, if haven´t this result it´s bad
You have the if and foreach backwards. First check if the count is the same to know that the post is valid, then show the results.
And instead of a loop, you can simply implode() $result:
if (count($result) == count($exp_post)) {
echo implode('<br>', $result);
} else {
echo "Invalid input";
}

Why the output is not a string

I tried many time, but I still don't understand why the output is not a string, anything wrong ? help me check it. The final output should be a uppercase name string
<html>
<p>
<?php
// Create an array and push on the names
// of your closest family and friends
$name = array();
array_push($name,"Mike");
array_push($name,"Jane");
array_push($name,"Jack");
array_push($name,"Nike");
array_push($name,"Ash");
array_push($name,"Chris");
array_push($name,"Zark");
// Sort the list
sort($name);
join(",",$name);
// Randomly select a winner!
$random = count($name,rand(0,7));
// Print the winner's name in ALL CAPS
$winner = strtoupper($random);
print($winner);
?>
</p>
</html>
$random = count($name,rand(0,7));
This line assigns the count of elements in $name. I don't know what else you expected to get back other than a number here.
What you really want:
echo strtoupper($name[array_rand($name)]);
http://php.net/manual/en/function.array-rand.php
Other Notes:
Your call to join() doesn't do anything useful since you're not doing anything with the return value.
Your call to sort is pointless if you're just picking a random entry later.
Pick a plural name for your array names so you know they are arrays. $names instead of $name.
If you know all of the array elements ahead of time, no need for array_push(), just use an array literal: array('Mike', 'Jane', /* etc */)
If you're outputting data into the context of HTML, always use htmlspecialchars() to make sure any reserved characters are escaped properly. This isn't a problem with the code you literally have here, but will be as soon as you want to output < or ".

Returning string value in php array

Its a simple problem but i dont remember how to solve it
i have this array:
$this->name = array('Daniel','Leinad','Leonard');
So i make a foreach on it, to return an array
foreach ($this->name as $names){
echo $names[0];
}
It returns
DLL
It returns the first letter from my strings in array.I would like to return the first value that is 'Daniel'
try this one :
foreach ($this->name as $names){
echo $names; //Daniel in first iteration
// echo $names[0]; will print 'D' in first iteration which is first character of 'Daniel'
}
echo $this->name[0];// gives only 'Daniel' which is the first value of array
Inside your loop, each entry in $this->name is now $names. So if you use echo $names; inside the loop, you'll print each name in turn. To get the first item in the array, instead of the loop use $this->name[0].
Edit: Maybe it makes sense to use more descriptive names for your variables.
For example $this->names_array and foreach ( $this->names_array as $current_name ) makes it clearer what you are doing.
Additional answer concerning your results :
You're getting the first letters of all entries, actually, because using a string as an array, like you do, allows you to browse its characters. In your case, character 0.
Use your iterative element to get the complete string everytime, the alias you created after as.
If you only want the first element, do use a browsing loop, just do $this->name[0]. Some references :
http://php.net/manual/fr/control-structures.foreach.php
http://us1.php.net/manual/fr/language.types.array.php

PHP Calculation in variables from foreach output

I have this code:
$fookerdos = '';
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos .= file_get_contents($someposoA);
//to print them i you want
print $fookerdos;
So my problem that for this code will outputs many numbers becouse of many files.
for example will out output this
3.5 -6.7 6.68 -0.2 and so on..
now i want all this numbers to make them (addition)
i know how to addition some 2-3 variables, but i additions many numbers that I even dont know how many they are.
for example
print "3.5 + "-6.7" "6.68" "-0.2";
Thx :)
Does each file contain only a single number, or can they have more than one numbers?
From your previous edits, it seems as if one file contain only a number.
In that case, you can store the values in an array and sum the numbers using array_sum() or perform any other calculation as needed.
Here is a sample code for you:
$fookerdos = array ();
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos[] = file_get_contents($somekerdos);
}
echo array_sum ($fookerdos);

excluding previously randomized integer, and randomize again without it

<?php
if (isset($_POST['Roll!'])) {
$sides = $_POST['sides'];
$rolled = rand(1,$sides);
echo "$rolled was rolled by the dice, it is now out!";
}
?>
This is the code I currently have. After rolling that number, however, I want it to roll again, but without the previously rolled number, until it has rolled all number except one, which would be the winning number. I have no idea how to go about doing that. Any ideas?
EDIT: I'm sorry, I should have been more clear, thank you all for the help so far, but I also need to echo each number rolled, such as
echo "$rolledArray[0] was rolled, it lost.\n";
echo "$rolledArray[1] was rolled, it lost.\n";
echo "$rolledArray[2] was rolled, it lost.\n";
echo "$rolledArray[3] was rolled, it lost.\n";
echo "$rolledArray[x] was rolled, it lost.\n";
echo "$rolledArray[x] was rolled, it lost.\n";
echo "$rolledArray[50?] was rolled, it lost.";
EDIT AGAIN: Also I only want them to have to click Roll! once, not multiple times until they've rolled all the numbers, meaning no need for session, I think, though I could be wrong, most of you are clearly more experienced than me.
Sorry, I should have mentioned that before as well.
To answer your direct question:
You can put all of the possible numbers into an array, and get a random index for that array. Once you have an index, remove the item from the array and redo the random over the smaller array:
$possible = range(1, $_POST['sides']); // build the possible values
$rolledIndex = rand (0, count($possible)); // get a random index
$rolled = $possible[$rolledIndex]; // get the rolled number
unset($possible[$rolledIndex]); // and remove the rolled nuber
// now you can simply redo the random:
$rolledIndex = rand (0, count($possible)); // get a random index on the smaller array
$rolled = $possible[$rolledIndex]; // get the 2nd rolled number
However, If you want to have a random order on the dice throws, simply use this:
// generate an array with all values from 1 to the posted value (e.g. 1,2,3,4,5,6)
$possible = range(1, $_POST['sides']);
// this reorders the array by random (e.g. 4,3,1,5,2,6)
$throwOrder = $possible;
shuffle($throwOrder);
print_r($throwOrder);
Now you can simply iterate over the $throwOrder array and have a random order of dice throws:
Array (
0 => 4,
1 => 3,
2 => 1,
3 => 5,
4 => 2,
5 => 6
)
Edit To get the desired output from the second method, simply do this:
// get the last index of the array of thrown dices
$lastIndex = count($throwOrder)-1;
// iterate through the array, printing the results
foreach ($throwOrder as $key => $rolled) {
// check if the current key matches the last key in the array
if ($key != $lastIndex) {
// if not, the number has lost
echo $rolled, " was rolled, it lost.\n";
} else {
// we have reached the last element of the array
echo $rolled, " was the last, it won.\n";
}
}
I think you need to have array $thrownNumbers, which holds every number previously thrown. And every new throw (OMG... the word), you check if it's in array. If yes, throw again. Simplest possible solution.
Edit: As for keeping the array during moving to another page, you can use:
$_SESSION
cookies (hm)
have serialized array as hidden value in form
There.
You can throw it in the $_SESSION to keep track of it between posts/request or append it to the URL and pass it yourself each time as a URI param.
<?php
if(!isset($_SESSION['numbers']){
$_SESSION['numbers'] = range(1,6); //same as array(1,2,3,4,5,6)
}
$numbers = $_SESSION['numbers'];
if(count($numbers)>1){ //is more than one number left
$rand_index = array_rand($numbers); //choose a number from an array, returns the index
print('you rolled '.$numbers[$rand_index].' loser'); // tell them they lost
unset($numbers[$rand_index]); //remove that element from the array
$_SESSION['numbers'] = $numbers; //set new array back to session
}else{
print(array_pop($numbers).' is the winner!'); //pop the remaining number out of the array and print it with winner notification
}
?>
edit: updated to session usage
It is not a bad idea to add to the URL if you use properly. The good side is that you don't store data in the session, the bad side is that the request is bigger each time. To avoid tampering you can use:
$url = 'numbers.php?throwed='.implode(',',$throwed).'&sign='.sha1(serialize($throwed).'mysecretpassword');
And use this to get check:
$throwed = explode(',',$_GET['throwed']);
$not_tampered = sha1(serialize($throwed).'mysecretpassword') == $_GET['sign'];
Just create an array (or other type of list) of all possible numbers and randomly order it. Then, instead of picking a new number each time just advance through the array until you get to the last but one.
Alternatively, you could just go straight to the last number in the list and that's the winner.
It depends on the situation, but creating an array with all the possible numbers for all the visitors in your web can be a very bad idea, sessions files can grow unnecessarily.
If they are like numbers from 1 to 10 I think it would be OK, but if they are numbers from 1 to 1 million creating arrays with those ranges saved in the session is pretty much a bad idea.
I think it's better to save the rolled results and generate a new one until it doesn't exist in the array.

Categories