a question about getting three random words out of a big string of say 200 words:
$trans = __("water paradise, chicken wing, banana beach, tree trunk")?>
// $trans becomes "water paradijs, kippenvleugel, bananen strand, boom tak"
// elements are separated by comma's and a space
Now imagine I want to get 5 random elements from that $trans string and echo that.
How can I do that? Code is welcome! Please keep this syntax in your answer:
$trans = the original string
$shufl = selective shuffle of 5 elements
contains e.g kippenvleugel, boom tak
You can do this by creating an array of strings using split, and then shuffling it with shuffle:
# Split the string into different elements
$strings = split(',', $trans);
# Shuffle the array
shuffle($strings);
# Select 5 elements
$shufl = array_slice($strings, 0, 5);
array_slice is then used to get the first 5 elements of the shuffled array. Another possibility is to use array_rand on the split array:
$shufl = array_rand(array_flip($strings), 5);
$array = explode ( ',',$trans);
shuffle($array);
for ( $i = 0 ; $i < 5 ; $i ++ ){
$shufl[] = $array[$i];
}
This will result in a $shufl array containing your 5 random elements.
Hope this helps :)
For better understanding. What is a random string?
Can it be:
'water paradijs' 'kippenvleugel' 'bananen strand'
or can it also be
'water strand' 'kippenvleugel bananen', etc.
?
Related
I have the following array:
["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"]
How can I extract the second last value in the array, then the second part of that value after the comma e.g. "Medical Ethics and Law,strandyear"?
This should result, for example, in 'strandyear'.
The actual value, not the position from the end, will be different for other arrays.
PHP 5.3.3...
What about the following ...
$secondLast = array_slice($source, -2, 1);
The PHP function array_slice can do the job in one line of code.
Then you 've got the second last entry from the original array. Now you can explode the string with a comma.
$parts = explode(",", $secondLast);
$strand = array_pop($parts);
The first line explodes the string by a comma. The second line gives you the last part (strand) of all exploded parts.
Try This,
First do json_decode()
then get secondLast then do strstr() to get value after comma and the do ltrim() thats it.
$str = '["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"]';
echo $str;
$array = json_decode($str);
$secondLast = $array[2];//count($array)-2
echo'<pre>';print_r($array);
echo $secondLast.'<pre>';
echo ltrim(strstr($secondLast, ','),',');
die;
OUTPUT:
["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"]
Array
(
[0] => theme
[1] => 1,strand
[2] => Medical Ethics and Law,strandyear
[3] => Year 3
)
Medical Ethics and Law,strandyear
strandyear
Best way to get the second last value in the array
end($array);
$second_last = prev($array);
after that you cant get the second part i.e the value after comma you can use
explode(separator,string) //function in PHP
$temp= explode(',', $second_last);//converted to an array
$second_part=$temp[1];
<?php
$a = ["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"];
$b = explode(',',$a[1]);
$c = $b[1];
var_dump($c);
// tring(6) "strand"
Use explode explode
Returns an array of strings, each of which is a substring of string
formed by splitting it on boundaries formed by the string delimiter.
usage: explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) : array
$arr = Array("theme","1,strand","Medical Ethics and Law,strandyear","Year 3");
$secondValueAfterComma = explode(',',$arr[2]);
echo $secondValueAfterComma[1];
You may do like
$arr = ["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"];
Here is your code to access 2nd last element
$value = $arr[count($arr)-2];
i want to get static length to get any random value from array.
PHP CODE:
in this below code how to get 5 random value from array?
$arr_history = array(23, 44,24,1,345,24,345,34,4,35,325,34,45,6457,57,12);
$lenght=5;
for ( $i = 1; $i < $lenght; $i++ )
echo array_rand($arr_history);
You can use array_rand() to pick 5 random keys and then use those to intersect with the array keys; this keeps the original array intact.
$values = array_intersect_key($arr_history, array_flip(array_rand($arr_history, 5)));
Demo
Alternatively, you can first shuffle the array in-place and then take the first or last 5 entries out:
shuffle($arr_history);
$values = array_slice($arr_history, -5);
This has the advantage that you can take multiple sets out consecutively without overlaps.
Try this :
$rand_value = array_rand($arr_history);
echo $rand_value;
REF: http://php.net/manual/en/function.array-rand.php
OR use :
shuffle($arr_history)
This will shuffle the order of the array : http://php.net/manual/en/function.shuffle.php
I am using str_split() to split a long strings into an array of length 16 each. And I'm assigning the returned array to one in my function. Like this:
$myarray = str_split($string, 16);
The problem is that I want the indexing of $myarray to start from a number other than 0, say 50. Currently I'm doing this:
foreach($myarray as $id => $value)
{
$myarray[$id + 50] = $value;
unset($myarray[$id]);
}
Is there a better solution? Because the arrays and strings I'm dealing with are very long. Thanks
You can use array_pad().
$myarray = str_split($string, 16);
$myarray = array_pad($myarray, -(size($myarray)+50), null);
It will fill the first 50 elements with nulls and push the rest of the array forward by 50 elements.
I have the following array:
$array = array(1,0,0,0,1,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,1,0,1);
I want split it up into individual arrays so that each array contains seven or less values.
So for example the first array will become:
$one = array(1,0,0,0,1,1,1)
$two = array(1,0,1,1,1,1,0)
$three = array(1,1,0,1,0,0,1);
$four = array(0,1);
Also how would you count the number of times 1 occurs in array one?
array_chunk() is what you are looking for.
$splitted = array_chunk($array, 7);
For counting the occurences I would be lazy. If your arrays only contain 1s or 0s, then a simple array_sum() would do:
print array_sum($splitted[0]); // for the first chunk
I want split it up into individual arrays so that each array contains seven or less values.
Use array_chunk(), which is made expressly for this purpose.
Also how would you count the number of times 1 occurs in array one?
Use array_count_values().
$one = array(1,0,0,0,1,1,1);
$one_counts = array_count_values($one);
print_r($one_counts);
// prints
Array
(
[0] => 3
[1] => 4
)
Assuming you want to preserve the contents of the array, I'd use array_slice() to extract the needed number of elements from the array, incrementing the '$offset' by the required count each time until the array was exhausted.
And as to your second question, try:
$num_ones=count(preg_grep(/^1$/,$array));
This question already has answers here:
How do I select 10 random things from a list in PHP?
(5 answers)
Closed 8 months ago.
From an array
$my_array = array('a','b','c','d','e');
I want to get two DIFFERENT random elements.
With the following code:
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
}
it is possible to get two times the same letter. I need to prevent this. I want to get always two different array elements. Can somebody tell me how to do that?
Thanks
array_rand() can take two parameters, the array and the number of (different) elements you want to pick.
mixed array_rand ( array $input [, int $num_req = 1 ] )
$my_array = array('a','b','c','d','e');
foreach( array_rand($my_array, 2) as $key ) {
echo $my_array[$key];
}
What about this?
$random = $my_array; // make a copy of the array
shuffle($random); // randomize the order
echo array_pop($random); // take the last element and remove it
echo array_pop($random); // s.a.
You could always remove the element that you selected the first time round, then you wouldn't pick it again. If you don't want to modify the array create a copy.
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
unset($my_array[$random]);
}
You can shuffle and then pick a slice of two. Use another variable if you want to keep the original array intact.
$your_array=[1,2,3,4,5,6,7];
shuffle($your_array); // randomize the order
$your_array = array_slice($your_array, 0, 2); //pick 2
foreach (array_intersect_key($arr, array_flip(array_rand($arr, 2))) as $k => $v) {
echo "$k:$v\n";
}
//or
list($a, $b) = array_values(array_intersect_key($arr, array_flip(array_rand($arr, 2))));
here's a simple function I use for pulling multiple random elements from an array.
function get_random_elements( $array, $limit=0 ){
shuffle($array);
if ( $limit > 0 ) {
$array = array_splice($array, 0, $limit);
}
return $array;
}
Here's how I did it. Hopefully this helps anyone confused.
$originalArray = array( 'first', 'second', 'third', 'fourth' );
$newArray= $originalArray;
shuffle( $newArray);
for ($i=0; $i<2; $i++) {
echo $newArray[$i];
}
Get the first random, then use a do..while loop to get the second:
$random1 = array_rand($my_array);
do {
$random2 = array_rand($my_array);
} while($random1 == $random2);
This will keep looping until random2 is not the same as random1