Using array_slice() to get first few values - php

I'd like to use an array_slice to get every value in an array iterated over, except for the current one, the one before it, and all the others until the end of the array.
So for example, say I have 5 elements:
[1, 2, 3, 4, 5]
I want a way for a condition to fire on 3, cut it out, and then also cut out 4 and 5. I have this, but I don't think it's correct:
$items = array_slice($items, $itemcount - 1);

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
So if you want to get the 3,4,5 your offset should be 2, because the array key ( starts from 0 ex: 0,1,2,3,4). i didn't use length in this one because i want to get it till the end (5)
$items = array_slice($items, 2);
If you want to grag 1,2 it should be like this. ( i use length 2 because i want to get the first 2 keys)
$items = array_slice($items, 0, 2);
Example

Related

How to get random item from array only from the specified keys (e.g x key first)

I have a array that i want to select two item as random, And two keys are selected between the key 2 and the key 8.
$arr = array=(1,2,3,4,5,6,7,8,9,10,11,12);
I can get two random item:
$rand_keys = array_rand($arr, 2);
$arr[$rand_keys[0]]; // one
$arr[$rand_keys[0]]; // two
In the above code, It is possible that selected items be from the entire array. Now i want to know how can I limit my choice?
In fact i want to get random item from this array:
array=(2,3,4,5,6,7,8);
You can use array_slice to first take a part of the array before you take random items from it
$part = array_slice($arr, 1, 7); // outputs array(2,3,4,5,6,7,8)

Getting the number of different values in a PHP array

I need to know the number of different values in an array. For example if it contains (5, 5, 5) then I should get 1. If it contains (4, 4, 2, 2) I should get 2. If (5, 5, 5, 5, 2, 2, 1, 5) then 3.
Is there a function that can achieve that directly in PHP?
echo count(array_unique($arr));
you can use array_unique which returns unique elements of array (result is also array type) and then count on result
Two simple ways to achieve that:
$diff_count = count(array_unique($input_arr));
$diff_count = count(array_flip($input_arr)); <-- recommended (performance)
array_unique() :
Removes duplicate values from an array - you can add adittional flags such as:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.
array_flip():
Exchanges all keys with their associated values in an array - so duplicates keys are overwritten and you get a final array with the unique values as keys.
Flipping it twice will result in an array with unique values and the highest keys there were in the original input array.
More reading:
array_unique.
array_flip.
Benchmark:
Since the array_flip uses only O(n) exactly its much faster - using an array of 10,000 numbers as an input:
array_unique + count: ~28.615 ms.
array_flip + count: ~0.5012 ms. (winner)
Is there a function that can achieve that directly in PHP?
The closest one would be array_unique() but here is a simple function to achieve what you are looking for:
$arr = array(5,5,5,5,2,2,1,5);
function array_diff_values( $array ) {
return count( array_unique($array) );
}
$count = array_diff_values( $arr );
result of $count is 3

PHP - counting an imploded array

I am trying to use sizeof or count to return the number of things inside the array, however whenever I use the $rank_ids2 to count rather than entering 1, 2, 3, 4, 67, 7 in manually, it just returns 1, but when I type them in the array directly, it counts 6 just fine!
$ranksAllowed = '|1|2|3|4|67|7|';
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
$rank_ids2 = implode(", ", $rank_ids);
$arrayofallowed = array($rank_ids2);
echo sizeof($arrayofallowed);
$rank_ids is just turning the |1|2|.. format into 1, 2
My first solution to your problem would be to initially define $ranksAllowed as an array instead of a pipe-character-delimited string:
$ranksAllowed = array(1, 2, 3, 4, 67, 7);
This would make more sense in almost any foreseeable situation. If for some reason you'd rather keep $ranksAllowed as a string...
Some simplification
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
can be simplified to:
$rank_ids = explode('|', trim($ranksAllowed, '|'));
Decide on string or array format
Right now it looks like you're trying to do 2 things at once (and achieving neither)
One possibility is you want to turn your pipe-delimited ("|1|2|3|...") string into a comma delimited string (like "1, 2, 3, ..."). In this case, you could simply do a string replace:
$commaDelimited = str_replace('|', ',', trim($ranksAllowed, '|'));
The other possibility (and I believe the one you're looking for) is to produce an array of all the allowable ranks, which you've already accomplished in an earlier step, but assigned to $rank_ids instead of $arrayofallowed:
$arrayofallowed = explode('|', trim($ranksAllowed, '|'));
//Should print out data in array-format, like you want
print_r($arrayofallowed);
//Echo the length of the array, should be 6
echo count($arrayofallowed);
implode converts an array to a string, so after everything you get this:
A string named $ranksAllowed that contains |1|2|3|4|67|7|
An array named $rank_ids that contains multiple elements, being them 1, 2, etc...
A string named $rank_ids2 that contains 1,2,3,4,67,7
An array named $arrayofallowed with only 1 element, being it the string inside $rank_ids2
To achieve a string that contains 1,2,3,4,67,7 from |1|2|3|4|67|7| you can just trim the | character as you do and replace | with ,. Is less CPU expensive.
$rank_ids2 = str_replace("|", ",", trim("|".$ranksAllowed."|", '|'));
If you want to count them you can explode it and count the elements:
$rank_ids2_array = explode(',', $rank_ids2);
echo sizeof($rank_ids2_array);
or with your code you can simply count the already exploded $rank_ids.
echo sizeof($rank_ids);
Try something like the following:
$ranksAllowed = '|1|2|3|4|5|67|7|';
$rank_ids = explode('|', trim($ranksAllowed, '|'));
echo count($rank_ids);
Just to explain the above, the $arrayofallowed is imploding the array of $rank_ids, creating a string. This will not give you the expected results when counted. If you simply count the $rank_ids (as explode() will leave you with an array), you should see the desired result of 7 items.
The $rank_ids is your array, and $arrayofallowed was a string.
Please see the sections of the PHP manual related to the implode() and explode() functions for more information.

Looking up keys for a multi-dimensional array

I have an array with a key and 3 values (day, start_time, end_time). I want to keep adding certain entries into this array while making sure each entry is unique. That means that every time I try to add an item into the array, I want to make sure it does not already exist in it. If it does exist, I want to be able to find the key that indicates that entry.
For example, this is the pre-existing array:
$array [0][0] = Monday
$array [0][1] = 2
$array [0][2] = 4
$array [1][0] = Tuesday
$array [1][1] = 3
$array [1][2] = 5
If I try to insert (Wednesday, 3, 5), then it should make the entry in the index 2.
If I try to insert (Monday, 2, 4), I need to be able to know that it is already in there and is indexed by 0.
How do I go about doing this?
I agree with the other answers here — it might be better to restructure your array so that there is no need to worry about duplication at all.
If you want to keep your current structure, however: use array_search.
$array = ...
$unique_check = array_search(array('Monday', 2, 4), $array);
if ( $unique_check === false )
// add to array
else
// $unique_check = the array key at which the existing matching element is located
Why not organize the array this way?
$array [Monday][0] = 2
$array [Monday][1] = 4
$array [Tuesday][0] = 3
$array [Tuesday][1] = 5

Random array special

how make special random array. i have array(1=>35,2=>25,3=>40). how make possibility that array show special elements. Ex.
If i want get 100 elements from array. it will be
35/100 +-10 - must bee 1 element,
25/100 +-10 = must be 2 element,
40/100 +-10 - must be 3 element.
Elements must be random, but most elements +-10. i know its possible make by this code:
$a = array_fill(1, 35, 1);
$b = array_fill(36, 60, 2);
$c = array_fill(61, 100, 3);
array looks like array(35 elements with value 1, 25 elements with value 2, 40 elements with value 3)
and using merge and array_rand i will get my code. But i don't want this code. it will be create 100 items. need optimization this code. it's possible. help. :-)
Are you looking for a weighted random array?
Check this example:
http://20bits.com/articles/random-weighted-elements-in-php/

Categories