PHP How to loop randomly through an array of placeholders - php

I have a search input in my wordpress site, which I want to display different placeholdes each time the page been refreshed. So I will have an array of the different values, the function that will loop randomly through the array, and I think my problem is with the result. I'm using a plugin for the search input, so to define for example that the placeholder would say 'hello', I need to do:
$item['textinput']= "hello";
So I need the result to be:
$item['textinput']= $placeholders;
I am adding the whole code:
$placeholders = array("yo i hio", "and him", "nayo jones");
function randominputs($input){
$i=1;
while($i<=20){
$randNum = rand(1,100);
if($input==$i){
$item['textinput']= $placeholders;
}
$i++;
}
}
Thanks

Use array_rand:
$placeholder = $placeholders[array_rand($placeholders)];

I would suggest adding the sizeof() call to your code.
For example if I wanted to call a random result from an array you could try...
$arr = array("1", "2", "3", "4", "5", "6", "7");
$len = sizeof($arr) - 1; // account for the 0 position
$rand = rand(0,$len);
echo $arr[$rand];

You can also use like:
$placeholders = array("yo i hio", "and him", "nayo jones");
$randomPlaceholder = array_rand($placeholders);
$item["textinput"] = $randomPlaceholder[0];

Related

How Can I Echo Out Array Items In An Organzied Way?

I want to echo out the content of this array in a 1, 2 way
$arr = array("name", "john", "lastname", "doe", "age", "55");
so I wish for it to look like
name = john
lastname = doe
age = 55
And my code currently looks like this
for ($x=0;$x<count($arr)/2;$x++) {
echo $arr[$x] . " = " . $arr[$x++];
}
But it does not work. The 2 elements of the variable have to be outputted within the same going through of the loop so I can't just concatenate them or something like that.
Your array should look like this :
$arr = array("name"=> "john", "lastname"=> "doe", "age"=> 55);
and then you can go like this :
foreach ($arr as $key => $val) {
echo $key , " = " , $val ;
}
It just needs a couple of small adjustments:
for ($x = 0; $x < count($arr); $x+=2) {
echo $arr[$x] . " = " . $arr[$x+1] . "<br/>";
}
Change the loop criteria so it'll get all the way to the end of the dataset.
Change the loop criteria so it'll increment $x 2 steps at a time, and ten just get the +1 for the
According to your question, it appears you want a line break between each data item. If this is for a web application, use <br/>. If it's for command-line or text-based output, use PHP_EOL.
However, there are other possible approaches using foreach which might be considered more elegant, as shown in the other answers here.
BTW, if you could have a more structured array using associative key-value pairs insteading of relying on index patterns e.g. array("name" => "john", "lastname" => "doe", "age" => 55); that would make your life easier in general, so if you have the freedom to make a change like that, I'd advise it.

Loop through an array (+100 values) [duplicate]

This question already has answers here:
Show the two elements in foreach loop in every iteration? [duplicate]
(4 answers)
Closed 1 year ago.
This is my array:
$my_array = array("1", "2", "3", "4");
I want to achieve something like this:
1 vs 2
3 vs 4
Because the length of my array is only 4 it was easy for me to do this:
echo $my_array[0]." vs ".$my_array[1];
echo "<br>";
echo $my_array[2]." vs ".$my_array[3];
But how can I achieve this if my array has more than 100 values? I also want to account for odd numbers of array elements.
You can use a "for" loop, with an increment of two for every loop :
$len = count($my_array);
for($i=0; $i<$len; $i=$i+2) {
echo $my_array[$i]." vs ".$my_array[$i+1]."<br/>;
}
If you're not sure your array always contains an even number of indexes, you can add a condition in order to ignore the last case if there is no more pair to do.
$len = count($my_array);
for($i=0; $i<$len; $i=$i+2) {
if($i !== $len-1) {
echo $my_array[$i]." vs ".$my_array[$i+1]."<br/>;
}
}
Sure, for loop is the obvious answer, but there are more interesting ones ;)
$my_array = ["1", "2", "3", "4"];
$new_array = array_map(
function($v) {return isset($v[1]) ? "$v[0] vs $v[1]<br/>" : null; },
array_chunk($my_array, 2)
);
print_r($new_array);
Output:
Array
(
[0] => 1 vs 2<br/>
[1] => 3 vs 4<br/>
)
You can use a for loop to loop through the array.
$my_array = array("1", "2", "3", "4","5","6");
for ($x = 0; $x < sizeof($my_array); $x = $x+2) {
echo $my_array[0+$x]." vs ".$my_array[1+$x];
echo "<br>";
}

Create an adjacency structure from a list of sequence

I would like to build an Adjacency List from my list of sequence in a php. The thing is, that my list of sequince is in array and it looks like this:
$arr = array("1", "1.1", "1.2", "2", "2.1", "2.1.1", "2.1.2");
Now, I would like to transform it so that it would be in a Adjanency list model, like this:
$arr1 = array("0", "1", "1", "0", "4", "5", "5");
So, my $arr1 will be representing a 'parentId' in the table for a tree view(jsTree).
Can please somebody point me to the right directon, or where should I start looking for a solution.
Thank you.
You could do something like this:
for ($i = 0; $i < count($arr); $i++) {
$splitString = explode(',', $arr[i]); //split the string on the point
if (strlen($splitString) > 1) {
$arr1[i] = $splitString[1]; // take the part after the point
}
else {
$arr1[i] = "0"; // no part after the point, so default to 0
}
}

PHP Count values of an array

Is there a way to count the values of a multidimensional array()?
$families = array
(
"Test"=>array
(
"test1",
"test2",
"test3"
)
);
So for instance, I'd want to count the 3 values within the array "Test"... ('test1', 'test2', 'test3')?
$families = array
(
"Test"=>array
(
"test1",
"test2",
"test3"
)
);
echo count($families["Test"]);
I think I've just come up with a rather different way of counting the elements of an (unlimited) MD array.
<?php
$array = array("ab", "cd", array("ef", "gh", array("ij")), "kl");
$i = 0;
array_walk_recursive($array, function() { global $i; return ++$i; });
echo $i;
?>
Perhaps not the most economical way of doing the count, but it seems to work! You could, inside the anonymous function, only add the element to the counted total if it had a non empty value, for example, if you wanted to extend the functionality. An example of something similar could be seen here:
<?php
$array = array("ab", "cd", array("ef", "gh", array("ij")), "kl");
$i = 0;
array_walk_recursive($array, function($value, $key) { global $i; if ($value == 'gh') ++$i; });
echo $i;
?>
The count method must get you there. Depending on what your actual problem is you maybe need to write some (recursive) loop to sum all items.
A static array:
echo 'Test has ' . count($families['test']) . ' family members';
If you don't know how long your array is going to be:
foreach($families as $familyName => $familyMembers)
{
echo $familyName . ' has got ' . count($familyMembers) . ' family members.';
}
function countArrayValues($ar, $count_arrays = false) {
$cnt = 0;
foreach ($ar as $key => $val) {
if (is_array($ar[$key])) {
if ($count_arrays)
$cnt++;
$cnt += countArrayValues($ar);
}
else
$cnt++;
}
return $cnt;
}
this is custom function written by me, just pass an array and you will get full count of values. This method wont count elements which are arrays if you pass second parameter as false, or you don't pass anything. Pass tru if you want to count them also.
$count = countArrayValues($your_array);

Find min/max values in a multidimensional array

I need to find the minimum and maximum in a multidimensional array in PHP, I have what I thought would work below but it keeps giving me a parse error, this is homework and I am not asking anyone to do it for me but I am a beginner and any help would be appreciated.
<?php
/* 2 dimensional array in PHP - strictly an array of arrays */
$multable[] = array("11", "12", "15", "22", "41", "42");
$multable[] = array("6", "7", "16", "17", "22", "23");
$multable[] = array("1", "15", "16", "20", "22", "3");
<table>
<?php
/* display a table from a 2D array */
for ($j=0;$j<3;$j++) {
print "<tr>";
for ($k=0;$k<6;$k++) {
echo "<td>",$multable[$j][$k],"</td>";
}
print "</tr>";
$max_value = 0;
foreach ($multable as $myMax) {
if ($max_value<$myMax) {
$max_value = $myMax;
}
}
echo $max_value;
?>
</table>
There is also a one-liner for that:
$max = max( array_map("max", $multable) );
use max() and min() functions of php.
Max:
<?php
$multable = array();
$multable[] = array("11", "12", "15", "22", "41", "42");
$multable[] = array("6", "7", "16", "17", "22", "23");
$multable[] = array("1", "15", "16", "20", "22", "3");
$max = -99999999;
foreach($multable as $sub){
$tempMax = max($sub);
if($tempMax > $max){
$max = $tempMax;
}
}
echo $max;
?>
You can figure out min :)
Your foreach iteration only does one dimension - each $myMax is one of your six element lists and not an individual scalar value. That's why your comparison doesn't work and the conditional is never true, you are trying to compare a scalar with an array. What you call $myMax would more appropriately be called $currentRow
This is ok because PHP has some functions to find the min and max of an array
http://us.php.net/manual/en/function.min.php
http://us.php.net/manual/en/function.max.php
$max_value = 0; $min_value = $multable[0][0];
foreach ($multable as $currentRow)
{
// COMPARE CURRENT ROW's MIN/MAX TO MIN/MAX_VALUE
// AND MAKE NEW ASSIGNMENT IF APPROPRIATE
}
Or hand this in and see what your teacher says:
function fComp ($f) {return function ($a,$b) use ($f) {return $f($a, $f($b));};}
$max = array_reduce($multable, fComp('max'), $multable[0][0]);
$min = array_reduce($multable, fComp('min'), $multable[0][0]);
echo "max: $max <br />";
echo "min: $min";
PS - in your earlier iterations to make the HTML table, it would be good form to lose the constants. Use count to get the length of the array instead - or better yet - use foreach like you do later on. (Even with foreach you would still need two of them nested, it doesn't iterate a 2-dimensional array element-by-element)
For Minimum value
echo min(array_map("min", $multable));
For Maximum Value
echo max(array_map("max", $multable));
$minArray = array();
foreach($arrayVal as $arrI=> $arrK)
{
if($arrK == min($arrayVal ) )
{
array_push($minArray , $arrayVal );
}
}
print_r($minArray);
Here you go :)
I do not recommend calling min() or max() on each subarray, then calling the function again on the reduced array. This is making too many calls and won't be most efficient.
Instead, flatten the indexed array just once with a spread&merge technique, then call min() or max() just once on the flattened array.
Code: (Demo)
$flat = array_merge(...$multable);
printf(
'Min: %d, Max: %d',
min($flat),
max($flat)
);
Output:
Min: 1, Max: 42
If you only need one or the other outcome, then don't bother with the temporary variable.
echo min(array_merge(...$multable));
Or
echo max(array_merge(...$multable));

Categories