I have a function which is called within a foreach loop and takes in two parameters, an integer, representing the number of times the loop has run and an array (of no fixed size).
I would like to return the value of the array key that is equal to the counter.
For example, if the array has four elements: A, B, C and D and the counter is equal to 2, it returns B. However, I'm trying to get the same result if the counter is equal to 6, 10, 14, 38, 3998 etc etc.
Is there a simple way to achieve this?
Any advice appreciated.
Thanks.
<?php
function foo($position, array $array)
{
return $array[$position % count($array)];
}
foreach ($array as $i => $whatever) {
$foo = foo($i, $whatever);
}
Note: I'm assuming you're looping over an array of arrays, and passing that to your function. If that's not the case, then just pass whatever array you need to pass instead of $whatever.
If you just use this function to iterate over the array, then you could also do
$iterator= new LimitIterator( // will limit the iterations
new InfiniteIterator( // will restart on end
new ArrayIterator( // allows array iteration
array('A','B', 'C', 'D'))), // the array to iterate over
0, 20); // start offset and iterations
foreach($iterator as $value) {
echo $value; // outputs ABCDABCDABCDABCDABCD
}
Related
How to quickly remove elements in an array that are < 5 apart from each other quickly.
example:
array(1, 3, 5, 8, 11, 15);
needs to return the following cause they are more than 5 if you calculate the difference:
array(1, 8, 15);
This seems like it should be a built-in function in php for this. But I'm baffled.
There's nothing built-in for this, but it's a pretty easy thing to accomplish.
First, sort your array, unless it's already sorted.
sort($your_array);
Initialize your result array with the first element, and then iterate the array. Each time you get to a value at least 5 greater than the previous value, add it to the result and reset the previous value to that value.
$result[] = $previous = reset($your_array);
foreach ($your_array as $value) {
if ($value - $previous >= 5) {
$result[] = $previous = $value;
}
}
I have a foreach loop like below code :
foreach($coupons as $k=>$c ){
//...
}
now, I would like to fetch two values in every loop .
for example :
first loop: 0,1
second loop: 2,3
third loop: 4,5
how can I do ?
Split array into chunks of size 2:
$chunks = array_chunk($coupons, 2);
foreach ($chunks as $chunk) {
if (2 == sizeof($chunk)) {
echo $chunk[0] . ',' . $chunk[1];
} else {
// if last chunk contains one element
echo $chunk[0];
}
}
If you want to preserve keys - use third parameter as true:
$chunks = array_chunk($coupons, 2, true);
print_r($chunks);
Why you don't use for loop like this :
$length = count($collection);
for($i = 0; $i < $length ; i+=2)
{
// Do something
}
First, I'm making the assumption you are not using PHP 7.
It is possible to do this however, it is highly, highly discouraged and will likely result in unexpected behavior within the loop. Writing a standard for-loop as suggested by #Rizier123 would be better.
Assuming you really want to do this, here's how:
Within any loop, PHP keeps an internal pointer to the iterable. You can change this pointer.
foreach($coupons as $k=>$c ){
// $k represents the current element
next($coupons); // move the internal array pointer by 1 space
$nextK = current($coupons);
prev($coupons);
}
For more details, look at the docs for the internal array pointer.
Again, as per the docs for foreach (emphasis mine):
Note: In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the
array. This means that you do not need to call reset() before a
foreach loop. As foreach relies on the internal array pointer in PHP
5, changing it within the loop may lead to unexpected behavior. In PHP
7, foreach does not use the internal array pointer.
Let's assume your array is something like $a below:
$a = [
"a"=>1,
"b"=>2,
"c"=>3,
"d"=>4,
"e"=>5,
"f"=>6,
"g"=>7,
"h"=>8,
"i"=>9
];
$b = array_chunk($a,2,true);
foreach ($b as $key=>$value) {
echo implode(',',$value) . '<br>';
}
First we split array into chunks (the parameter true preserves the keys) and then we do a foreach loop. Thanks to the use of implode(), you do not need a conditional statement.
well this'd be 1 way of doing it:
$keys=array_keys($coupons);
for($i=0;$i<count($keys);++$i){
$current=$coupons[$keys[$i]];
$next=(isset($keys[$i+1])?$coupons[$keys[$i+1]]:NULL);
}
now the current value is in $current and the next value is in $next and the current key is in $keys[$i] and the next key is in $keys[$i+1] , and so on.
I have associative array as follows:
array(
[random_key_1] => 30,
[random_key_2] => 27,
[random_key_3] => 25,
[random_key_4] => 25,
[random_key_5] => 25,
[random_key_6] => 22,
);
The array is already sorted and I don't know key names. I would like to get top 3 elements. But simple:
array_slice($array, 0, 3);
would not work in my case because the fourth and the fifth element should be returned as well.
Is there any built-in function or maybe I should write it from scratch? I reckon this should be some recursive function to check consecutive elements.
Maybe this is what you want to do.
Get the top elements values, and then intersect them with the array to preserve the keys.
// gets the unique top 3 values
$top_values = array_slice(array_unique($array), 0, 3);
// intersects the original array with the top 3 values
$top_values_with_keys_and_duplicates = array_intersect($array, $top_values);
Your best bet is to grab the top three, then iterate over the rest, checking if the next element is equal to the last. If it is, grab it, otherwise stop iteration.
Something like this should work:
$top = array_slice($array, 0, 3);
foreach( array_slice( $array, 4) as $el) {
if( $el === $top[2]) {
$top[] = $el;
} else {
break;
}
}
Note you could also just use the array pointers with reset(), current() and next() to grab the top 3, then continue iterating until the current element doesn't equal the last element.
I have an array that contains other arrays of US colleges broken down by the first letter of the alphabet. I've setup a test page so that you can see the array using print_r. That page is:
http://apps.richardmethod.com/Prehealth/Newpublic/test.php
In order to create that array, I used the following code:
$alphabetized = array();
foreach (range('A', 'Z') as $letter) {
// create new array based on letter
$alphabetized[$letter] = array();
// loop through results and add to array
foreach ( $users as $user ) {
$firstletter = substr($user->Schoolname, 0, 1);
if ( $letter == $firstletter ) {
array_unshift( $alphabetized[$letter], $user );
}
}
}
Now, I want to split the array so that a certain range of letters is in each array. For example,
arrayABCEFGH - would contain the schools that begin with the letters A, B, C, D, E, F, G, and H.
My question is, should I modify the code above so that I achieve this before I do one big array, OR should I do it after?
And here is the big question . . if so, how? :-)
Thanks in advance for any help. It's greatly appreciated.
First off, the code to generate the array can be made easier by only iteratating over $users:
$alphabetized = array();
// loop through results and add to array
foreach ($users as $user) {
$firstletter = strtoupper($user->Schoolname[0]);
$alphabetized[$firstletter][] = $user;
}
// sort by first letter (optional)
ksort($alphabetized);
To retrieve the first 8 entries you could use array_slice:
array_slice($alphabetized, 0, 8);
Assuming that all first letters are actually used and you used ksort() on the full array that also gives you from A - H. Otherwise you have to use array_intersect_key() and the flipped range of letters you wish to query on.
array_intersect_key($alphabetized, array_flip(range('A', 'H')));
If you don't need a full copy of the array, then you should encapsulate the above code in a function that has an array as its argument ($letterRange), which will hold the specific array identifiers (letters) to be in the final array.
Then you would need to encapsulate the code within the foreach using an if block:
if (in_array($letter, $letterRange)) { ... }
This would result in an array only containing the letter arrays for the specified letters in $letterRange.
You could write a simple function that takes an array, and an array of keys to extract from that array, and returns an array containing just those keys and their values. A sort of array_slice for non-numeric keys:
function values_at($array, $keys) {
return array_intersect_key($array, array_flip($keys));
}
Which you can then call like this to get what you want out of your alphabetized list:
$arrayABCDEFGH = values_at($alphabetized, range('A','H'));
Hi I am coding a system in which I need a function to get and remove the first element of the array. This array has numbers i.e.
0,1,2,3,4,5
how can I loop through this array and with each pass get the value and then remove that from the array so at the end of 5 rounds the array will be empty.
Thanks in advance
You can use array_shift for this:
while (($num = array_shift($arr)) !== NULL) {
// use $num
}
You might try using foreach/unset, instead of array_shift.
$array = array(0, 1, 2, 3, 4, 5);
foreach($array as $value)
{
// with each pass get the value
// use method to doSomethingWithValue($value);
echo $value;
// and then remove that from the array
unset($array[$value]);
}
//so at the end of 6 rounds the array will be empty
assert('empty($array) /* Array must be empty. */');
?>