I have an array, and I don't know how may elements there are in the array. It could be 1, it could be 500, but I need the maximum amount to elements to be 21.
I know I can check the length using count(), but how do I chop the rest off if it is too long? Thanks.
You can use SplFixedArray it a good way to manage fixed size array .....
$array = new SplFixedArray(21);
Example
$array = SplFixedArray::fromArray($array);
$array->setSize(21);
See PHP Documentation
Try this code:
if(count($array) > 21){
$subarray = array_slice($array, 0, 21);
}
Explanation:
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
If your array is $arr then:
$subArray = array_slice($arr,0,21);
You can use array_slice to chop off the exceeding portion.
if(count($array) > 21){
$array = array_slice($array, 0, 21);
}
http://php.net/manual/function.array-slice.php
you need to use array_slice by specifying the offset as 0, and length as 21.
if(count($your_array) > 21){
$new_array = array_slice($your_array, 0, 21);
}
You can use array_splice to remove the elements beyond what you need
Related
I have this code which stores values in $products. I'm not sure if $products is an array or other thing.
I need to remove the first 100 values.
// Get all products
$products = Product::getProducts(1, 0, 1000000, 'id_product', 'DESC', false, true, $context);
if (is_array($products))
$products = array_slice($product, 100);
Refer to this page to get in deep.
According to array_slice() menu, the signature is:
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
Since OP wants to remove first 100 elements, it should be:
$first_100_elements = array_slice($products, 0, 100);
First of all, you need to know if the return type of method Product::getProducts(). You can do it using gettype() or even var_dump().
If it is an array, use something like this:
$productsWithoutFirst100 = array_slice($product, 100);
I will get all the elements of the array, from hundredth element, till the end, excluding the first 100 (from key 0 to 99).
It is a collection of products, so it can be a object that implements Iterable interface. If it is the case, the array_slice function will not work. You can put the object into a foreach, and work on it:
$productsArrayWithoutFirst100 = [];
foreach($products as $key =>$product){
if($key >= 100) $productsArrayWithoutFirst100 = $product;
}
Thats a idea, but there is another ways to achieve it. Hope it helps.
I am using str_split() to split a long strings into an array of length 16 each. And I'm assigning the returned array to one in my function. Like this:
$myarray = str_split($string, 16);
The problem is that I want the indexing of $myarray to start from a number other than 0, say 50. Currently I'm doing this:
foreach($myarray as $id => $value)
{
$myarray[$id + 50] = $value;
unset($myarray[$id]);
}
Is there a better solution? Because the arrays and strings I'm dealing with are very long. Thanks
You can use array_pad().
$myarray = str_split($string, 16);
$myarray = array_pad($myarray, -(size($myarray)+50), null);
It will fill the first 50 elements with nulls and push the rest of the array forward by 50 elements.
I have an array which could be of any size coming from users.
The maximum size of values in each request to the API is 100 (from 0 - 99), a user could have ( it varies could be 64 or 137 or .... ) 234 values in his own array, what I want is to get the first hundred values, the next 100 values, then the next 34 values stored in an array or a string.
Something like ;
First Hundred : 0 - 99 //100
Second Hundred : 100 - 199 //100
Next Values : 200 - 234 //34
In each instance the values get appended to a string as seen below.
$lookupString = "";
//$notfm = one-dim array of values
for( $i = 0; $i <= 99; $i++ ){
$lookupString .= $notfm[$i].",";
}
$lookup = "http://api.lol.com/1/?user_ids=".$lookupString;
Can someone help me on this? I think this is easy but I'm missing something. Thanks.
Sample of the json encoded array can be found here
You want to use the array_chunk function.
http://php.net/manual/en/function.array-chunk.php
$request_bits = array_chunk($notfm, 100)
foreach ($request_bits as $request_bit) {
...
}
Alternately, you can set a separate condition to make the request when the counter is 100, empty the array of IDs, and empty the counter, but unless memory management is a huge issue array_chunk will do the trick.
You can use array_chunk() and implode().
$input_array;
// Split into chunks of 100
$chunks = array_chunk($input_array, 100);
foreach ($chunks as $chunk)
{
// Build the lookup string
$lookupString = implode(",", $chunk);
// DO LOOKUP HERE
}
Whenever I need to work with arrays, I open up the array functions manual page. A quick scan through the descriptions can often point you to an array function that does exactly what you want.
You want to get familiar with range() and array_chunk():
// make an array with all the numbers from 1 to 1000
$notfm = range(1,1000);
// make groups of 100 each
$chunks = array_chunk($notfm, 100);
// loop over each chunk of 100
foreach ($chunks as $lookupArray) {
$lookupString = implode(',', $lookupArray);
$lookup = "http://api.example.com/1/?user_ids=" . rawurlencode($lookupString);
// do stuff
}
Documentation: range(), array_chunk(), implode()
You can use array_slice
$first = array_slice( $input, 0, 100 );
$second = array_slice( $input, 100, 100 );
$third = array_slice( $input, 200, 34 );
And after goes the way what you want.
I'm removing a set of elements with array slice, from e certain offset to the end.
How can I get the elements that were removed, in a different array?
You just need to use array_slice twice:
$begin = array_slice($array, 0, 5);
$end = array_slice($array, 5);
Now $begin contains the first 5 elements of $array, and $end contains the rest.
array_slice will return an array containing the elements that were removed. You can also use array_diff to find the elements that were not removed.
$original = array('1','2','3','4','5');
$sliced = array_slice($original,1); // 2, 3, 4, 5
$diff = array_diff($original,$sliced); // 1
$arr = array('1st', '1st');
The above $arr has 2 items , I want to repeat $arr so that it's populated with 4 items
Is there a single call in PHP?
array_fill function should help:
array array_fill ( int $start_index, int $num, mixed $value )
Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.
In your case code will look like:
$arr = array_fill(0, 4, '1st');
$arr = array('1st', '1st');
$arr = array_merge($arr, $arr);
This is a more general answer. In PHP 5.6+ you can use the "splat" operator (...) to repeat the array an arbitrary number of times:
array_merge(...array_fill(0, $n, $arr));
Where $n is any integer.