Push the output of a for loop into an array - php

I am trying to push the output of a for loop into an array but I am not being able to do so. Following is the code that I have written:
<?php
$n = 14;
for ($i = 2; $i <= $n; $i++)
{
for ($j = 2; $j <= $n; $j++)
{
if ($i%$j == 0) // if remainder of $i divided by $j is equal to zero, break.
{
break;
}
}
if ($i == $j) //
{
$form = $i;
//echo $form;
$numArray = array();
array_push($numArray, $form); // Here I am trying to push the contents from the `$form` variable into the `$numArray`
print_r($numArray);
}
}
?>
The output that I obtain through this is:
Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 5 ) Array ( [0] => 7 ) Array ( [0] => 11 ) Array ( [0] => 13 )
Here, we see that the array index basically remains the same, so it has no scope for future use. So, how can I make this seem like as shown below:
Array ( [0] => 2 ) Array ( [1] => 3 ) Array ( [2] => 5 ) Array ( [3] => 7 ) Array ( [4] => 11 ) Array ( [5] => 13 )
Please note that, $n in the code can be any number less than 101 and greater than 1. Thank you for your precious time put into reading and trying to helping me out. :)

The $numArray should be declared once, not every time in the loop. And you can simply add value to the array by using expression like: $numArray[] = $i;
Try this code:
<?php
$numArray = array();
$n = 14;
for ($i = 2; $i <= $n; $i++) {
for ($j = 2; $j <= $n; $j++) {
if ($i % $j == 0) { // if remainder of $i divided by $j is equal to zero, break.
break;
}
}
if ($i == $j) {
$numArray[] = $i;
}
}
print_r($numArray);

Related

PHP array multidimensional: foreach starting from determinate level

I have a multidimensional array that looks like the one below:
Array
(
[results] => Array
(
[0] => Array
(
[hotel_code] => 15ad7a
[checkout] => 2018-04-26
[checkin] => 2018-04-24
[destination_code] => 1c6e0
[products] => Array
.... etc ....
)
[1] => Array
(
[hotel_code] => 193c6c
[checkout] => 2018-04-26
[checkin] => 2018-04-24
[destination_code] => 1c6e0
[products] => Array
.... etc ....
)
Wanting to create a simple pagination of the results, taking from the array 15 records at a time, through the following code I can recover the first 15 records.
$i = 0;
foreach($data['results'] as $key=>$val){
$i++;
$selez_hotel_code = '' . $val['hotel_code'] . '';
if($i == 15) break;
}
Now, how can I get the next 15 values from the array?
I tried to start the foreach directly from record 15, setting it as follows
$i = 0;
foreach($data['results'][14]['hotel_code'] as $val){
$i++;
$selez_hotel_code = '' . $val . '';
if($i == 15) break;
}
but it did not work.
You could use for loop, to specify the start and the end:
$start = 15 ;
$length = 15 ;
$max = count($data['results']);
for ($idx = $start; $idx < $start + $length && $idx < $max; $idx++) {
$val = $data['results'][$idx]['hotel_code'] ;
$selez_hotel_code = $val ;
}
Note that I've added a verification to avoid to loop over the maximum of results ($idx < $max).
You can use $_GET to paginate. Just have a for loop that uses this param if set, 0 if not. Something like this:
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;
for ($i = $page; $i < ($page + 15); $i++) {
// $data['results'][$i] . . .
}
And when clicking on "next page" or whatever you're using, set the page param

After for-loop, returned array is wrong

I have something like that:
$n = 2;
$items = array();
$result = array(); // new array with random items
$random_items = array_rand( $items, $n );
for( $f=0; $f<=$n; $f++ ) {
$result[] = $items[$random_items[$f]];
}
$items is sth like
Array ( [0] => file1.jpg [1] => file2.png [2] => file3.jpg ... and so on )
This is working OK... but if I set $n to 1 then the script is not working or working incorrectly!
If $n == 2 (or more) the result array have last element's value empty
Array ( [0] => 20141125-17826a4b34.png [1] => 20141125-27fe57561d.jpg [2] => )
If $n == 1 (exactly) the result array is like
Array ( [0] => [1] => )
The result array should be the same format as items array but only with $n random items.
Thanks in advance!
Working
if( $n > 1 ) {
for( $f=0; $f<$n; $f++ ) {
$result[] = $items[$random_items[$f]];
}
}
elseif( $n == 1 ) {
$result[0] = $items[$random_items];
}
You should $f < $n instead of $f <= $n
for( $f=0; $f < $n; $f++ ) {
$result[] = $items[$random_items[$f]];
}
Because, when you're using $f <= $n its running up to 0,1 (when, $n = 1) OR 0,1,2 (when $n = 2) and you're missing the last indexed element.
When picking only one entry, array_rand() returns the key for a random
entry(not array).Otherwise, an array of keys for the random entries is returned.
So, This means, when you're using $n = 1, then $random_items is just a value(not array). eg.
for $n = 1, $random_items = 4;
but for $n >= 2, $random_items = [1, 6, 3, 6];

PHP Function for Comparing Elements in Different Arrays

I have two arrays like so (however there can be more or less than 2 (any amount)):
[0] => Array
(
[assessedUsers] => Array
(
[0] => Array
(
[scores] => Array
(
[0] => 10
[1] => 10
[2] => 10
[3] => 10
)
)
[1] => Array
(
[scores] => Array
(
[0] => 9
[1] => 10
[2] => 0
[3] => 9
)
)
)
)
Where the length of the scores array is always the same in both arrays.
I would like to take each element from each array, one by one, and average them, then append them into a new array.
For example, the output of my desired function would look like this:
[1] => Array
(
[scores] => Array
(
[0] => 9.5
[1] => 10
[2] => 5
[3] => 9.5
)
)
Is there a function that can do this, or do I need a couple nested for() loops? If I need to use forl loops how would I go about doing it? I'm a little confused on the logic behind it.
Currently what I have is:
for ($i = 0; $i < sizeof($data["assessedUsers"]); $i++) {
for ($j = 0; $j < sizeof($data["assessedUsers"][$i]["scores"]); $j++) {
}
}
and I'm a little confused as to what to where to go next. Thanks in advance!
$mean = array_map( function($a, $b) { return ($a + $b) / 2; },
$data['assessedUsers'][0]['scores'],
$data['assessedUsers'][1]['scores']
);
var_dump($mean);
And append $mean anywhere you want. Or do you have more than 2 arrays? You did not state it in your question.
ps: for any number of subarrays
$arr = array(
array('scores' => array(10,10,10,10)),
array('scores' => array(9,10,0,9)),
array('scores' => array(1,2,3,4))
);
// remove arrays from the key
$tmp = call_user_func_array( function() { return func_get_args(); },
array_map( function($a) { return $a['scores']; }, $arr)
);
// add arrays by each element
$mean = array_map( function($val, $ind) use($tmp) {
$sum = 0;
foreach($tmp as $i => $t)
$sum += $t[$ind];
return $sum / ($i + 1);
}, $tmp[0], array_keys($tmp[0]));
var_dump($mean);
Probably two loops:
$newarray();
foreach($main_array as $user) {
foreach($user['assessedUser'][0]['scores'] as $score_key => $user0_value) {
$user1_value = $user['assessedUser'][1]['scores'][$score_key];
$average = ($user1_value + $user0_value) / 2;
... stuff into new array
}
}
I have solution for you, hope this help :)
$scores = array();
for ($i = 0; $i < sizeof($data["assessedUsers"]); $i++) {
for ($j = 0; $j < sizeof($data["assessedUsers"][$i]["scores"]); $j++) {
if(isset($scores[$j])){
$scores[$j] = ($scores[$j] + $data["assessedUsers"][$i]["scores"][$j]) / ($i +1);
}else{
$scores[] = $data["assessedUsers"][$i]["scores"][$j];
}
}
}
$scores[] = $scores;
view Example :)
http://codepad.org/upPjMEym

Simple array operation in PHP

Let's say I have following array:
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 8
)
[2] => Array
(
[0] => c
[1] => 16
)
[3] => Array
(
[0] => d
[1] => 21
)
....
)
Numbers in inner array are generated randomly from range (0, 100) and they don't repeat.
I would like to create a loop, which will iterate from 0 to 100 and check if loop iteration is equal to inner number of above array. Excepted result is array with 100 elements:
Array
(
[0] => const
[1] => a
[2] => const
[3] => const
[4] => const
[5] => const
[6] => const
[7] => const
[8] => b
[9] => const
[10] => const
.
.
[16] => c
[17] => const
.
.
[21] => d
[22] => const
[23] => const
.
.
)
What I need is something like:
for ($i=0; $i < 100; $i++) {
if($i === $name[$i][1]) {
$new_array[] = $name[$i][0];
} else {
$new_array[] = 'const';
}
}
But I can't get it working, thus I need some help.
I am not an English native speaker, so hopefully you understand what I would like to achieve. Thanks for any help.
you need a nested loop like:
for ($i=0; $i < 100; $i++):
$found = false;
foreach($name as $array):
if($array[1] === $i):
$found = true;
$new_array[] = $array[0];
endif;
endforeach;
if(!$found):
$new_array[] = 'const';
endif;
endfor;
The reason it doesn't work is because each time $i is incremented you're trying to make a match in $name[$i], and not checking all of the arrays in $name, the simplest solution I can think of (and to perform the least number of iterations) would be to do something like:
$new_array = array();
foreach ($name as $n) {
$new_array[$n[1]] = $n[0];
}
for ($i=0; $i<100; $i++) {
if (!isset($new_array[$i])) {
$new_array[$i] = 'const';
}
}
ksort($new_array);
So first of all, loop through your $name array, and set up your $new_array with the the key => value pair (eg. [1] => 'a', [8] => 'b'), then in the for loop just check if the key ($i) has already been set, and if not, set it with the value 'const'. Finally, sort the $new_array by its keys.
The number of iterations in this example is count($name) + 100, whereas a nested loop for example would be 100 * count($name).
use
for ($i=0; $i < 100; $i++) {
if($i === $name[$i][1]) {
$new_array[$i] = $name[$i][0];
}
else{
$new_array[$i] = 'const';
}
}
for ($i = 0; $i < count($name); ++$i) {
if ($name[$i][1] === $i) {
$name[$i] = $name[$i][0];
} else {
$name[$i] = 'const';
}
}
Why do u use Identical operator instead of Equal
for ($i=0; $i < 100; $i++) {
if($i == $name[$i][1]) {
$new_array[] = $name[$i][0];
} else {
$new_array[] = 'const';
}
}

php numbers script array loop

I try to write a script and a problem. Can you let me know if you know how i can do this or ask someone if they know how can this be possibe.
Max numbers which can be selected 1 to 20 numbers. it can loop and select any number between 1-20
ignore these numbers e.g. 1,2,4,6,9,12 this will be array which can change.
each array line can have upto 4 numbers
Each array line needs to be unique
5.I need to have around 10 arrays unique
Max 2 numbers can match previous numbers see below.
How can i go about doing this. Any help would be great.
e.g.
Array(
[0] => Array
(
[0] => 3
[1] => 16
[2] => 22
[3] => 24
)
[1] => Array
(
[0] => 3
[1] => 16
[2] => 7
[3] => 13
)
[2] => Array
(
[0] => 20
[1] => 17
[2] => 10
[3] => 18
)
)
This not allow as some array match each other
Array(
[0] => Array
(
[0] => 3
[1] => 16
[2] => 22
[3] => 24
)
[1] => Array - cant have this as 3 of the numbers matchs the previous array.only two numbers can match.
(
[0] => 3
[1] => 16
[2] => 22
[3] => 13
)
[2] => Array
(
[0] => 20
[1] => 17
[2] => 10
[3] => 18
)
)
Thank you.
This seems to satisfy your conditions: http://codepad.viper-7.com/WHkQeD
<?php
$num_arrays = 10; $num_elements = 4;
$min = 1; $max = 20;
$exclude_numbers = array( 1, 4, 6); // Add numbers here to exclude
$answer = array();
for( $i = 0; $i < $num_arrays; $i++)
{
$answer[$i] = array();
for( $j = 0; $j < $num_elements; $j++)
{
do
{
$current = rand( $min, $max);
// If the previous array exists and there are more than two common elements when we add the $current element, continue
if( isset( $answer[$i-1]) && count( array_intersect( $answer[$i-1], array_merge( $answer[$i], array( $current))) > 2)
{
continue;
}
} while( in_array( $current, $exclude_numbers) || in_array( $current, $answer[$i]));
$answer[$i][$j] = $current;
}
}
var_dump( $answer);
Edit: Here is a complete solution that satisfies all of your criteria.
Demo
<?php
$num_arrays = 10; $num_elements = 4;
$min = 1; $max = 20;
$exclude_numbers = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
$answer = array();
for( $i = 0; $i < $num_arrays; $i++)
{
$answer[$i] = array();
for( $j = 0; $j < $num_elements; $j++)
{
do
{
// Get a random element
$current = rand( $min, $max);
$new_array = array_merge( $answer[$i], array( $current));
// If the previous array has more than two common elements (because of the added $current), get a new $current
if( isset( $answer[$i-1]) && count( array_intersect( $answer[$i-1], $new_array)) > 2)
{
$answer[$i] = array_diff( $new_array, $answer[$i-1]);
$j = count( $answer[$i]) - 1;
continue;
}
} while( in_array( $current, $exclude_numbers) || in_array( $current, $answer[$i]));
$answer[$i][$j] = $current;
// If the array is complete, we need to check for unique arrays
if( count( $answer[$i]) == $num_elements)
{
$k = $i - 1;
while( $k >= 0)
{
if( count( array_diff( $answer[$k], $answer[$i])) == 0)
{
// This array is the same as a previous one, start over
$answer[$i] = array();
$j = -1;
break;
}
$k--;
}
// Optionally sort each array
sort( $answer[$i]);
}
}
}
var_dump( $answer);
somthing like:
function generate_list($max, $forbidden)
{
$list = array();
while(count($list) < 4)
{
$new = rand(1, $max);
if(in_array($new, $forbidden))
{
continue;
}
$list[] = $new;
$forbidden[] = $new;
}
return $list;
}
function count_max_same($new_list, $old_lists)
{
$max_same = 0;
foreach($old_lists as $current_list)
{
$max_same = max($max_same, count(array_intersect($new_list, $old_lists)));
}
return $max_same;
}
function generate_unique_lists($count_of_lists, $max, $forbidden, $max_same = 2, $max_tries = 1000)
{
$lists = array();
while($max_tries-- AND count($lists) < $count_of_lists)
{
$new_list = generate_list($max, $forbidden);
if(count_max_same($new_list, $lists) <= $max_same)
{
$lists[] = $new_list;
}
}
return $lists;
}

Categories