Remove first 100 element of variable? - php

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.

Related

PHP counter excluding zeros

In PHP I have an array that returns a set of values. I want to count the number of instances in the array excluding the zeros. Basically I'm creating an average total column in a table and if a person did not contribute then I don't want to count them. I have the total amount, just not the total count that contributes. Any help please?
You can do it with count and array_filter method.
count gives you the total number of elements in an array.
array_filter removes all elements whose value represents false(such as 0 empty string etc.) from an array;
Eg:
echo count(array_filter($your_array));
Use foreach to iterate the array and count the items that are not "zero".
$counter = 0;
foreach ($array as $item) {
if ( /* determine if $item is "not zero" */ ) {
++$counter;
}
}
echo $counter;
That's all I can tell you based on the information you provided.
You can give a callback function to array_filter as the second parameter. (http://php.net/manual/en/function.array-filter.php)
array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
So you can do something like this:
function isNonZero(int $num){
return $num !== 0;
}
count(array_filter([0,1,2,3,4], "isNonZero")); // => 4

Get the highest number value 'Magento'

I have this function and i want to get the highest number value.
$array is out-putting 20, 50, 40.
I want to print 50 only not the other 2.
Tried everything nothing is working.
foreach ($products as $product) {
$originalPriceCat = $product->getPrice();
$finalPriceCat = $product->getFinalPrice();
if ($originalPriceCat > $finalPriceCat) {
$CalculatedPrice = ($originalPriceCat - $finalPriceCat) * 100 /$originalPriceCat;
$array = array($CalculatedPrice);
echo round(max($array));
}
}
The following code will surely solve your problem
$CalculatedPrice = array();
foreach ($products as $product) {
$originalPriceCat = $product->getPrice();
$finalPriceCat = $product->getFinalPrice();
if ($originalPriceCat > $finalPriceCat) {
$CalculatedPrice[] = ($originalPriceCat - $finalPriceCat) * 100 / $originalPriceCat;
}
}
echo round(max($CalculatedPrice));
Take a look at this php function: max
max ( array $values ) : mixed
max ( mixed $value1 [, mixed $... ] ) : mixed
If the first and only parameter is an array, max() returns the highest
value in that array. If at least two parameters are provided, max()
returns the biggest of these values.
max() returns the parameter value considered "highest" according to standard comparisons.
If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.
If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.

Reindex array by increasing and decreasing all of top indexes

First, I have to list what I have found
How to Remove Array Element and Then Re-Index Array?
PHP reindex array?
They did not make sense in my case. I have fallen into ridiculous request and I've force to find the way out, then please don't ask me why I want to do that.
I have below array
$input = array(
0=>array('a', 'b'=>array('c')),
1=>array('b', 'c'=>array('d')),
2=>array('c', 'd'=>array('e')),
);
I want to increase all of keys by 1 or decrease by 1 (acceptable to index is negative int number)
Here is expected result
//after increased by 1
$input = array(
1=>array('a', 'b'=>array('c')),
2=>array('b', 'c'=>array('d')),
3=>array('c', 'd'=>array('e')),
);
or
//after decreased by 1
$input = array(
-1=>array('a', 'b'=>array('c')),
0=>array('b', 'c'=>array('d')),
1=>array('c', 'd'=>array('e')),
);
The closet answer I got here from raina77ow in the question
How to increase by 1 all keys in an array?
$arr = array_flip(array_map(function($el){ return $el + 1; }, array_flip($arr)));
But it just works with simple array key pairs, if array value is other array instead of a string or integer, it would raise the exception
array_flip(): Can only flip STRING and INTEGER values!
The thing what I could think is handling the array to swap roster manually, it would be the final way if there were not any other workaround.
Any help is appreciated!
This should so the trick.
// Increase by one
$input = array_combine(
array_map(function($value) {
return $value += 1;
}, array_keys($input)), $input
);
The easiest way would probably to use foreach and make a new array... like this:
$new = array();
foreach($arr as $k=>$v) {
$new[$k+1] = $v; // either increase
$new[$k-1] = $v; // or decrease
}
You can also perform the operation by passing the original array by reference.

Set array to have a maximum of 21 elements

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

PHP: How do I check the contents of an array for my string?

I a string that is coming from my database table say $needle.
If te needle is not in my array, then I want to add it to my array.
If it IS in my array then so long as it is in only twice, then I still
want to add it to my array (so three times will be the maximum)
In order to check to see is if $needle is in my $haystack array, do I
need to loop through the array with strpos() or is there a quicker method ?
There are many needles in the table so I start by looping through
the select result.
This is the schematic of what I am trying to do...
$haystack = array();
while( $row = mysql_fetch_assoc($result)) {
$needle = $row['data'];
$num = no. of times $needle is in $haystack // $haystack is an array
if ($num < 3 ) {
$$haystack[] = $needle; // hopfully this adds the needle
}
} // end while. Get next needle.
Does anyone know how do I do this bit:
$num = no. of times $needle is in $haystack
thanks
You can use array_count_values() to first generate a map containing the frequency for each value, and then only increment the value if the value count in the map was < 3, for instance:
$original_values_count = array_count_values($values);
foreach ($values as $value)
if ($original_values_count[$value] < 3)
$values[] = $value;
As looping cannot be completely avoided, I'd say it's a good idea to opt for using a native PHP function in terms of speed, compared to looping all values manually.
Did you mean array_count_values() to return the occurrences of all the unique values?
<?php
$a=array("Cat","Dog","Horse","Dog");
print_r(array_count_values($a));
?>
The output of the code above will be:
Array (
[Cat] => 1,
[Dog] => 2,
[Horse] => 1
)
There is also array_map() function, which applies given function to every element of array.
Maybe something like the following? Just changing Miek's code a little.
$haystack_count = array_count_values($haystack);
if ($haystack_count[$needle] < 3)
$haystack[] = $needle;

Categories