I have the following array
$example=array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
$limit=4 // 4 at the beginning only...
//it used to get incremented automatically to 8,12,16....
At first i want 1,2,3,4as an output for which i have done
foreach($example as $eg)
{
if($eg>$limit)
continue;
}
and i am easily getting 1,2,3,4 at the first then 1,2,3,4,5,6,7,8 then1,2,3,4,5,6,7,8,9,10,11,12
But now i what i want is 1,2,3,4 at the very beginning then 5,6,7,8 then 9,10,11,12 lyk this... how can i get that???
please do help me... :)
AS the
foreach($example as $eg)
{
if($eg>$limit)
continue;
}
is returning only 1,2,3,4 at $limit=4 and 1,2,3,4,5,6,7,8 at $limit=8
i need 1,2,3,4 at $limit=4 and 5,6,7,8 at $limit=8
Have you tried using the helpful built-in functions?
array_chunk($example,$limit);
Alternatively, for more page-like behaviour:
$pagenum = 2; // change based on page
$offset = $pagenum * $limit;
array_slice($example,$offset,$limit);
You would first chunk the array so each chunk has 4 elements, then loop through each chunk:
To change the numbers shown depending on which group, you could do:
$group = $_GET['group'];
$items = array_chunk($example, ceil(count($example)/4)[$group-1];
echo implode(", ", $items);
Then you can go to
yoursite.com/page.php?group=1
And it will output
1, 2, 3, 4
And when you go to
yoursite.com/page.php?group=2
It will output
5, 6, 7, 8
etc.
You can try something like this
$example=array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
$limit = 8;
$limit -= 4;
for($i = $limit; $i < ($limit + 4); $i++)
{
echo $example[$i].' ';
}
Output
//for $limit 4 output 1 2 3 4
//for $limit 8 output 5 6 7 8
//for $limit 16 output 13 14 15 16
Related
I have a pagination which renders some pages. I have a setting where the user can define how many pages are to be displayed as numbers in the pagination nav. The first and last number are always visible. Now if the user wants to have 3 numbers on the nav and assuming that i am now in the page 7, then it should look like this:
1 ... 6 7 8 ... 12
If the user wants four items then it should look like that:
1 ... 6 7 8 9 ... 12
Up until now i have the following which gives me 3 before and after the current page
$maxLinks = 3;
$currentPageNumber = 7;
$pages = [];
$pages[] = 1;
for($i = max(2, $currentPageNumber - $maxLinks); $i <= min($currentPageNumber + $maxLinks, 12 - 1); $i++) {
$pages[] = $i;
}
$pages[] = 12;
foreach ($pages as $key => $page) {
$newPage = '...';
if (($key === 0) && $pages[1] !== $page + 1) {
array_splice( $pages, 1, 0, $newPage );
}
$itemBeforeLast = count($pages)-2;
if (is_numeric($pages[$itemBeforeLast]) && ($key === $itemBeforeLast) && $pages[$itemBeforeLast + 1] !== $pages[$itemBeforeLast] + 1) {
array_splice( $pages, $itemBeforeLast +1, 0, $newPage );
}
}
This gives me back the following:
But i only want to get 3 or 4 numbers between the dots (this changes based on the value that the user gives in the settings ($maxLinks variable))
Any help is deeply appreciated
Best regards
As you add them to both sides, you need to divide by 2. Also, remove 1 to account for the current page. Then you just need to account for the possibility of having a non-even number of links to the left&right by rounding (down for the left, up for the right).
And end up with:
for($i = max(2, $currentPageNumber - floor(($maxLinks-1)/2));
$i <= min($currentPageNumber + ceil(($maxLinks-1)/2), 12 - 1); $i++)
Pair every two arrays is the task – store it, print it and repeat it until it becomes one value.
input : 1, 2, 3, 4, 5, 6, 8, 9, 9
output: 3 7 11 17 9
10 28 9
38 9
47
My code is working fine in this scenario. Somehow I managed to add 0 at the end for pairless elements. But my main focus is how can I make the logic even more clearer to avoid grumpy offset errors?.
My code:
function sumForTwos($arr)
{
if(count($arr) == 1){
exit;
}
else {
$sum = [];
for ($i = 0; $i < count($arr) -1; $i++)
{
//logic to add last array for odd count to avoid offset error
if(count($arr) % 2 == 1){ $arr[count($arr)] = 0; }
//logic to pair arrays
if($i != 0) { $i++; }
$sum = $arr[$i] + $arr[$i + 1];
$total[] = $sum;
echo $sum . " ";
}
echo "<br>";
$arr = $total;
//Recursion function
sumForTwos($arr);
}
}
sumForTwos([1, 2, 3, 4, 5, 6, 8, 9, 9]);
You can adopt an iterative approach and look at this as processing each level of values with every next level have 1 value less from total values. In other words, you can look at this as a breadth first search going level by level. Hence, you can use a queue data structure processing each level one at a time.
You can use PHP's SplQueue class to implement this. Note that we can advantage of this class as it acts as a double-ended queue with the help of below 4 operations:
enqueue - Enqueues value at the end of the queue.
dequeue - Dequeues value from the top of the queue.
push - Pushes value at the end of the doubly linked list(here, queue is implemented as doubly linked list).
pop - Pops a node from the end of the doubly linked list.
Most certainly, all the above 4 operations can be done in O(1) time.
Algorithm:
Add all array elements to queue.
We will loop till the queue size is greater than 1.
Now, if queue level size is odd, pop the last one and keep it in buffer(in a variable).
Add all pairwise elements by dequeueing 2 at a time and enqueue their addition for next level.
After level iteration, add the last element back if the previous level size was odd.
Print those added elements and echo new lines for each level accordingly.
Snippet:
<?php
function sumForTwos($arr){
if(count($arr) == 1){
echo $arr[0];
return;
}
$queue = new SplQueue();
foreach($arr as $val){
$queue->enqueue($val); // add elements to queue
}
while($queue->count() > 1){
$size = $queue->count();
$last = false;
if($size % 2 == 1){
$last = $queue->pop(); // pop the last odd element from the queue to make queue size even
$size--;
}
for($i = 0; $i < $size; $i += 2){
$first = $queue->dequeue();
$second = $queue->dequeue();
echo $first + $second," ";
$queue->enqueue($first + $second);
}
if($last !== false){// again add the last odd one out element if it exists
echo $last; // echo it too
$queue->push($last);
}
echo PHP_EOL;// new line
}
}
sumForTwos([1, 2, 3, 4, 5, 6, 8, 9, 9]);
Demo: http://sandbox.onlinephpfunctions.com/code/5b9f6d4c9291693ac7cf204af42d1f0ed852bdf9
Does this do what you want?
function pairBySums($inputArray)
{
if (sizeof($inputArray) % 2 == 1) {
$lastEntry = array_pop($inputArray); //$inputArray now has even number of elements
}
$answer = [];
for ($ii = 0; $ii < sizeof($inputArray) / 2; $ii++) {
$firstIndexOfPair = $ii * 2; // 0 maps to 0, 1 maps to 2, 3 maps to 4 etc
$secondIndexOfPair = $firstIndexOfPair + 1; // 0 maps to 1, 1 maps to 3, 2 maps to 5 etc
$answer[$ii] = $inputArray[$firstIndexOfPair] + $inputArray[$secondIndexOfPair];
}
if (isset($lastEntry)) {
array_push($answer, $lastEntry);
}
echo implode(' ', $answer) . "<br>";
if (sizeof($answer) > 1) {
pairBySums($answer);
}
}
The algorithm makes sure it operates on an even array and then appends the odd entry back on the array if there is one.
$input = [1, 2, 3, 4, 5, 6, 8, 9, 9];
pairBySums($input);
produces:
3 7 11 17 9
10 28 9
38 9
47
With an even number of items,
$input = [1, 2, 3, 4, 5, 6, 8, 9];
pairBySums($input);
produces:
3 7 11 17
10 28
38
I want to get elements from an array like this: get first three element, then four elements, then again three elements, and again four, and so on in a loop.
For example:
0 1 2
3 4 5 6
7 8 9
10 11 12 13
and so on....
I tried something like this:
foreach($items as $key => $item) {
if($key <= 2) {
echo 'test';
}
if($key > 2 && $key < 6) {
echo 'other test';
}
if($key > 6 && $key < 9) {
echo 'test';
}
}
However, I don't want to use if() like these, because I don't know how many items will be in the array: it comes from a database.
I think, I need something like array_chunk($items, 3) but for size parameter I need 3 and 4 in loop
Could be like this you can make another array of specifying the number of elements you want in each iteration.
<?php
$number_of_elements = [3,4,3,4];
$your_array = ['a', 'b','c','d','e'];
foreach($number_of_elements as $number){
for($i = 0; $i<=$number; $i++){
$result = $your_array[$i];
print_r($result);
}
print_r('<br>');
}
In JavaScript you can solve your problem using a for loop and the built in slice function of the array.
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let offset = 0;
for(let i = 0; i < array.length;){
offset = offset === 3 ? 4 : 3;
const subArray = array.slice(i, i + offset);
console.log(subArray);
i += offset;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Given a non-empty array, return true if there is a place to split the array so that the sum of the numbers on one side is equal to the sum of the numbers on the other side.
Break the problem up into smaller problems.
The array we will be using is:
$array = [1, 2, 3, 4, 5];
First thing first:
Understand the problem
In order to compare the left side with the right side you need to split the array until the sums of both sides are equal, or until there are no more items to sum.
Visually that would look something like this:
• ••••
•• •••
••• ••
•••• •
Problem: Can the array be split into two parts?
It is always a good idea to find out if what you are trying to do is even possible, or if doing it even makes sense.
With this problem we need at least 2 items in the array in order to split it into two parts. So, if the array has fewer than 2 items then we can safely return false and call it a day:
if (count($array) < 2) {
return false;
}
Problem: How to go through the array
The array needs to be split after each item in the array. So, we need to go through the array item by item.
| • | • | • | • | • |
0 1 2 3 4 5
We only need to split the array at 1, 2, 3 and 4. In other words, we should start after the first item and stop before the last item:
$length = count($array);
for ($i = 1; $i < $length; $i++) {
echo "Split after {$i}\n";
}
Problem: How to get the left/right side from the array
Getting the left and right side is a simple matter of extracting them from the array.
$left = array_slice($array, 0, $i);
$right = array_slice($array, $i);
If you put that into the loop and output it you will get something like this:
1 | 2 3 4 5
1 2 | 3 4 5
1 2 3 | 4 5
1 2 3 4 | 5
Problem: Sum and compare
PHP has a array_sum() function that sums values in arrays:
if (array_sum($left) === array_sum($right)) {
return true;
}
One solution
function my_func($array) {
if (count($array) < 2) {
return false;
}
$length = count($array);
for ($i = 1; $i < $length; $i++) {
$left = array_slice($array, 0, $i);
$right = array_slice($array, $i);
if (array_sum($left) === array_sum($right)) {
return true;
}
}
return false;
}
var_dump(my_func([1, 2, 3, 4, 5])); // false
var_dump(my_func([7, 1, 2, 3, 1])); // true: 7 = (1 + 2 + 3 + 1)
(Assuming our input array contains numbers.)
Start by adding all the elements of the array to each other (total sum). Then iterate through the array and add each element to each other as we go (cumulative sum). If during our iteration we discover that our cumulative sum is equal to half the total sum, we know that the other members of the array will also add up to the half sum, and hence the array can be split.
<?php
function can_split(array $numbers) {
$total_sum = array_sum($numbers);
$half_sum = $total_sum / 2;
$cumulative_sum = 0;
foreach($numbers as $num) {
$cumulative_sum += $num;
if($cumulative_sum == $half_sum)
return true;
}
}
var_dump(can_split(array(1))); // null
var_dump(can_split(array(1,2,3))); // true
var_dump(can_split(array(10,1,9))); // true
var_dump(can_split(array(3,5,9))); // null
var_dump(can_split(array(1.5,2,3,3,3.5))); // true
what i want to do is something like memory game, but I keep cannot get the same number with the out put
$numbers = range(1, 15);
shuffle($numbers);
foreach($numbers as $key){
echo $numbers[array_rand($numbers)];
break;
}
now the out put will be something like this
4 2 3 3
1 5 3 6
2 3 4 5
10 9 8 10
but how to I do it as rand array and with same 2 array number, which is i can match the number.
what i want in out put is
2 3 1 4
3 4 2 1
5 6 9 7
7 9 6 5
so like this i can get the match in 2 same number
any idea how to do it?
thanks
Your question is a bit confusing and vague. I extrapolate that you want to shuffle and display an array of numbers, two of each, in random order. To do that:
<?php
$numbers = range(1, 5);
$numbers = array_merge($numbers, $numbers);
shuffle($numbers);
echo implode(' ', $numbers);
This outputs, for instance, 3 5 1 5 1 2 3 4 2 4.
The array_rand() call in the foreach in your code makes absolutely no sense. If the above isn't what you wanted, please revise your question to be clearer.
First you have to do an array with couple values
// Generate array with values from 1 to 8
$arNumbers = range(1, 8);
// Duplicate the array so get copy of each number
$arNumbers = array_merge($arNumbers, $arNumbers);
// Shuffle the array
shuffle($arNumbers);
// And now display them
foreach($arNumbers as $nNumber)
{
// Do some business
}
Hope it helps :)
Try this. It is a simple way.
$numbers=range(1, 15);
//Get 4 unique random keys from $numbers array.
$rand_keys = array_rand($numbers, 4);
//print out the random numbers using the
//random keys.
foreach ($rand_keys as $k=>$i) {
echo $numbers[$i]." ";
}
Hope this will helps you...
If I get you correctly, you can achieve what you want to do with the following:
// make sure these are even numbers
$rows = 4;
$cols = 4;
$set = range(1, ($rows * $cols) / 2);
$numbers = array_merge($set, $set);
shuffle($numbers);
foreach (array_chunk($numbers, $cols) as $row) {
foreach ($row as $col) {
printf('%-5d', $col);
}
echo "\n";
}
Outputs:
3 7 2 1
4 6 8 5
6 3 8 4
2 5 7 1
Do something like:
$numbers = range(1, 15);
shuffle($numbers);
$used_numbers = array();
foreach($numbers as $key){
$this_number = $numbers[array_rand($numbers)];
$used_numbers[] = $this_number;
echo $this_number;
break;
}
$_SESSION['numbers'] = $used_numbers;
Then you can use the $_SESSION to access the numbers on another page (after reload perhaps), or use the same $used_numbers array to access them.
If you try:
$numbers = range(1, 15);
shuffle($numbers);
$used_numbers = array();
foreach($numbers as $key){
$this_number = $numbers[array_rand($numbers)];
$used_numbers[] = $this_number;
echo $this_number;
break;
}
echo '<br />';
foreach($used_numbers AS $number) {
echo $number;
}
You will see it returns the same number.