Randomizing My Array elements [duplicate] - php

This question already has answers here:
Displaying and Randomising php Arrays
(4 answers)
Closed 9 years ago.
How do i randomize my array elements and limit number of items to be displayed to 5
My code is:
while($row = mysql_fetch_assoc($result))
{
$new_array[] = $row;
}
echo '<pre>'; print_r(($new_array));

Easiest solution...
array_rand($array, 5);
PHP array_rand()

shuffle($array);
$pointer = 0;
foreach($array as $value) {
if($pointer > 4) break;
echo $value;
$pointer++
}
shuffle will randomize your array, then you start a pointer at 0 and increment it in your foreach loop, if you the pointer is more than 4 you break the foreach loop
as another solution, you could use a for loop
shuffle($array);
for($i = 0; $i < 5; $i++) {
echo $array[$i];
}
and one more solution for limiting, since you're pulling the array for your database by a query, you can limit the number of rows returned by a number you choose by adding LIMIT 5 at the end of your query.

Related

how to filter multiple array value with for loop in php? [duplicate]

This question already has answers here:
How to filter an array by a condition
(9 answers)
Closed 5 years ago.
Output must be "This is a testing string sample". it is correct for small array filter with index value if filter array value are more than 100 values we can't assign static index number.How can be loop to filter to my base array. i know can use array_diff but i just learn how work with for loop.
<?php
$arr = array("This","is","testing","a","string",";","sample");
$filter = array(";","a");
for($i=0; $i < count($arr); $i++){
if($arr[$i] == $filter[0] || $arr[$i] == $filter[1]){
continue;
}
echo "$arr[$i] ";
}
?>
You could filter multiple values from an array using array_diff. For this case, you don't need an loop.
$filtered = array_diff($arr, $filter);
In general, there's an function, called array_filter to filter values from an array given a predicate.
$filtered = array_filter($arr, function ($item) use ($filter) {
return !in_array($item, $filter);
});
To print your result, you could just use join to combine the whole array with a "glue".
echo join(' ', $filtered);
To fix your example, you could also loop over your filter and use continue 2, to continue the outer loop. But this is very bad practice and leads to unreadable code. So don't do this! A better solution would be an "found" flag and another check after the inner loop, if the flag is set...
for($i=0; $i < count($arr); $i++){
for ($j = 0; $j < count($filter); $j++) {
if ($arr[$i] == $filter[$j]) {
continue 2;
}
}
echo "$arr[$i] ";
}
Use in_array
foreach ($arr as $item) {
if (in_array($item, $filter) {
continue;
}
echo $item, ' ';
}

Average of even numbers in array with for/while loop PHP [duplicate]

This question already has answers here:
Math average with php
(11 answers)
Closed 6 years ago.
I need to get the average of all the even numbers in this array:
$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983);
Can someone please help me? I'm already trying over an hour.
I have to do it with a for/while loop.
Use array_sum() and count()
$aReeks = array(23,245,1,2,12,-10,46,6,66,9999,-55,348,56,6,66,983);
echo array_sum($Reeks) /count($aReeks);
you can get the array with only the even number this way
foreach($aReeks as $key => $value) if($key&1) unset($aReeks[$key]);
and then
echo array_sum($Reeks) /count($aReeks);
$count = 0;
$average = 0;
foreach ($aReeks as $value)
{
$count++;
$average += $value;
}
$average = $average/$count;
echo "average: {$average}<br>";

can we use foreach() for two different arrays at once? [duplicate]

This question already has answers here:
Two arrays in foreach loop
(24 answers)
Closed 8 years ago.
I am facing problem when I am trying to insert values from array to mysql database.
foreach ( $_POST['product_id'] as $key=>$value AND $_POST['discount'] as $key1=>$discount) { }
check the above given code where I am going wrong?
You can use a regular for loop as long as the indexes match:
$count = count($_POST['product_id']);
for($i = 0; $i < $count; $i++) {
echo $_POST['product_id'][$i];
echo $_POST['discount'][$i];
}
use array_map this will loop through all keys in all arrays provided simultaneously.
array_map(function(){
$args = func_get_args();
foreach($args as $k => $v) {
echo $v;
}
}, $arr1, $arr2 ...);

Removing elements from an array in php [duplicate]

This question already has answers here:
Removing a value from a PHP Array
(3 answers)
Closed 8 years ago.
I have an array that looks like this
$hours_worked = array('23',0,'24',0)
What want to do is to loop through the array and remove the element that contains 0
What I have so far is:
for($i = 0; $i < count($hours_worked); $i++)
{
if($hours_worked[$i] === 0 )
{
unset($hours_worked[$i]);
}
}
However the result I get is $hours_worked = array(23,24,0). I.e. it does not remove the final element from the array. Any ideas?
The problem with this code is that you are calculating count($hours_worked) on each iteration; once you remove an item the count will decrease, which means that for each item removed the loop will terminate before seeing one item at the end of the array. So an immediate way to fix it would be to pull the count out of the loop:
$count = count($hours_worked);
for($i = 0; $i < $count; $i++) {
// ...
}
That said, the code can be further improved. For one you should always use foreach instead of for -- this makes the code work on all arrays instead of just numerically indexed ones, and is also immune to counting problems:
foreach ($hours_worked as $key => $value) {
if ($value === 0) unset($hours_worked[$key]);
}
You might also want to use array_diff for this kind of work because it's an easy one-liner:
$hours_worked = array('23',0,'24',0);
$hours_worked = array_diff($hours_worked, array(0)); // removes the zeroes
If you choose to do this, be aware of how array_diff compares items:
Two elements are considered equal if and only if (string) $elem1 ===
(string) $elem2. In words: when the string representation is the
same.
Try foreach loops instead
$new_array = array();
foreach($hours_worked as $hour) {
if($hour != '0') {
$new_array[] = $hour;
}
}
// $new_array should contain array(23, 24)

PHP - how many times [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to find the repeating elements in an array?
If I have this array : array("hey", "test", "hey");
And I want to count how many times I have the word "hey", how can I do that?
Wouldn't it be great if there were a function like array_count_values?
</sarcasm>
Some example code of usage:
$arr = array(...);
$valCounts = array_count_values( $arr );
echo $valCounts['hey'];
I highly recommend browsing php.net and, in-particular, learning the array functions.
$count = 0;
foreach($array as $item) {
if($item == 'hey') {
$count++;
}
}
print $count;
The command is array_count_values. Check
http://www.php.net/manual/en/function.array-count-values.php
You just need to loop over the array.
$x = 0;
foreach (array("hey","test","hey") as $value) {
if ($value === "hey") $x++;
}
For a less efficient, but shorter, solution, you could use array_count_value.
$counts = array_count_values(array("hey","test","hey"));
$x = $counts["hey"];

Categories