PHP keep first 6 items in an array and drop the rest - php

I am wondering how I can drop any array items that come after a certain number like 6. Is there something in PHP that enables you do do it? Or is it a custom function that needs to be written

You could use array_slice for this purpose. For example:
$testArray = range(0, 10);
// Ensure there are at least six items in the source array.
if(count($testArray) >= 6) {
// Grab the first six items.
$firstSixItemsFromArray = array_slice($testArray, 0, 6);
}

If you're looking to take the first six elements of an array, based on position in the array, then array_slice or array_splice is the way to go.
array_splice($array, 6);
If you want to keep all elements with value less than 6, you could do something like:
$array = array_filter($array, function($v) { return $v <= 6; });

Related

How to return an array of random keys?

Let me ask you how to return any three random numbers into the array that is different from the other numbers in the array.
$checkrandom=array(1,2,3,4);
for($i=0;$i<3;$i++){
$random=RAND(1,10);
if(!in_array($random,$checkrandom)){
array_push($checkrandom,$random);
}else{
//do something
}
}
Rather than guess numbers and add them if they don't already exist, this creates an array of the remaining numbers (using a combination of range() and array_diff()). It then picks numbers out of that array (using shuffle() and array_shift()) and adds them to the end of $checkrandom.
$checkrandom=array(1,2,3,4);
$numbers = array_diff(range(1,10), $checkrandom);
for($i=0;$i<3;$i++){
shuffle($numbers);
$checkrandom[]=array_shift($numbers);
}
print_r($checkrandom);
Or, as deceze pointed out, just shuffle the remaining array and use array_slice() to extract the first 3 numbers...
$checkrandom=array(1,2,3,4);
$numbers = array_diff(range(1,10), $checkrandom);
shuffle($numbers);
$checkrandom = array_merge($checkrandom, array_slice($numbers, 0, 3));
print_r($checkrandom);

Counting a number and push each number into an array

I am trying to figure out how to count a number that I pull from query string and push each into an array. so if the number is 3, I want to push 1, 2 and 3 as separate numbers into the array. The below code does not work:
$number = $_GET['tics'];
$items = array();
for($numbers = 0; $numbers<$number; $numbers++) {
$items[] = $numbers;
}
var_dump shows an empty array with this code. any idea how to make this work?
I want the key to be "numbers" and the values to be 1, 2, 3 etc..
I am sure this is explained many times already on stack, but when searching I found only examples that was way to advanced for someone like me
you can use range()
Returns an array of elements from start to end, inclusive.
$number = (int) $_GET['tics'];
$items = range(1, $number);
You can use http://php.net/manual/en/function.range.php to generate a list of numbers from min to max.
<?php
$number = 5;
// Do validation on $number before passing it to range.
$result = range(1, $number);
print_r($result);
For starters, your loop is incorrect.
If you pass $number = 3
for ($numbers = 0; $numbers < $number; $numbers++) {
Will give you 0, 1, 2. You need to change it to the following:
for ($numbers = 1; $numbers <= $number; $numbers++) {
This will give you 1, 2, 3.
Anyway, entertaining another idea here, if range() as mentioned by the other answers is not what you require.
I want the key to be "numbers" and the values to be 1, 2, 3 etc..
It's not exactly clear what you mean by this, but I'm guessing you might want the array keys to be the value of $numbers? In which case, you can modify your code as follows:
$number = (int)$_GET['tics'];
$items = array();
for ($numbers = 1; $numbers <= $number; $numbers++) {
$items[$numbers] = $numbers;
}
Your code should somewhat work as intended anyway (the numbers will be incorrect). The reason it doesn't is probably that $_GET['tics'] has no value. Ensure that you do indeed have tics in the $_GET array, and that you aren't actually POSTing (in which case you need $_POST['tics'] instead).
If you change $_GET in your code to $_POST and it still doesn't work, then tics is either not set or does not have a value greater than 0.

Quick way to filter elements out of an array that are x numbers apart

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;
}
}

PHP shuffle with seed?

How can I make the php shuffle function use a seed, so that when I use the same seed, the shuffle function will output the same array. I read that shuffle is automatically seeded. Is there a way to get the seed of that shuffle used, or how can I create/mimic shuffle with a custom seed?
You can't retrieve the seed used by shuffle, but you can simulate shuffle and fix your own seed:
$array = range(1, 10);
function seededShuffle(array &$array, $seed) {
mt_srand($seed);
$size = count($array);
for ($i = 0; $i < $size; ++$i) {
list($chunk) = array_splice($array, mt_rand(0, $size-1), 1);
array_push($array, $chunk);
}
}
$seed = date('Ymd');
seededShuffle($array, $seed);
var_dump($array);
This will set a different seed each day, but throughout the day it will use the same seed and shuffle the array in the same order; tomorrow will be a different random shuffle to today
For today (6th June 2015), the sequence should be
3, 6, 9, 2, 7, 1, 8, 5, 10, 4
PHP does not have shuffling with seeding, but you can do this instead:
$an_array = array('a','b','c','d');
$indices = array(0,1,2,3);
// shuffle the indices and use them as shuffling seed
shuffle($indices);
// then whenever you want to produce exactly same shuffle use the pre-computed shuffled indices
function shuffle_precomputed($a, $shuffled_indices)
{
$b = $a; // copy array
foreach ($shuffled_indices as $i1=>$i2) $a[$i2] = $b[$i1];
return $a;
}
use like this:
$shuffled_array = shuffle_precomputed($an_array, $indices);
You can even use the factoradic number system to transform the $shuffled_indices array to/from a unique integer number that can be used as a unique seed, then simply compute the shuffle from the factoradic number to be used in shuffle_precomputed function.
For additional shuffle variations for PHP you may want to see:
PHP - shuffle only part of an array
Efficiently pick n random elements from PHP array (without shuffle)

What's the most efficient way to array_pop() the last n elements in an array?

What's an efficient way to pop the last n elements in an array?
Here's one:
$arr = range(1,10);
$n = 2;
$popped_array = array();
for ($i=0; $i < $n; $i++) {
$popped_array[] = array_pop($arr);
}
print_r($popped_array); // returns array(10,9);
Is there a more efficient way?
Use array_splice():
If you're trying to remove the last n elements, use the following function:
function array_pop_n(array $arr, $n) {
return array_splice($arr, 0, -$n);
}
Demo
If you want to retrieve only the last n elements, then you can use the following function:
function array_pop_n(array $arr, $n) {
array_splice($arr,0,-$n);
return $arr;
}
Demo
It's important to note, looking at the other answers, that array_slice will leave the original array alone, so it will still contain the elements at the end, and array_splice will mutate the original array, removing the elements at the beginning (though in the example given, the function creates a copy, so the original array still would contain all elements). If you want something that literally mimics array_pop (and you don't require the order to be reversed, as it is in your OP), then do the following.
$arr = range(1, 10);
$n = 2;
$popped_array = array_slice($arr, -$n);
$arr = array_slice($arr, 0, -$n);
print_r($popped_array); // returns array(9,10);
print_r($arr); // returns array(1,2,3,4,5,6,7,8);
If you require $popped_array to be reversed, array_reverse it, or just pop it like your original example, it's efficient enough as is and much more direct.
Why not use array_slice. You can give a start and a length, so if you do 2 from the end you will get the last two items in the array:
$arr = range(1,10);
$n = 2;
$start = count($arr) - $n;
print_r(array_slice($arr, $start, $n));
Thanks for the array_slice comments. I don't know why that didn't immediately come to mind.
It looks (to me) like the easiest way is:
$arr = range(1,10);
$n = 2;
$popped_array = array_slice($arr,-$n);
print_r($popped_array); // returns array(10,9);

Categories