Count values left in Array - php

I need to figure out how to get the remaining values left in an Array.
Example: I have an array that randomly get two values. I want to get how many are left in that array after removing it.
If i remove 5 values from the array, and have a total of 20 return value 15.
Edit: If i have 52 cards in a deck, I draw 2 cards I have 50. If I draw two more cards i have 48.
I need to track how many "cards" are in the dealers array.

This should work:
$deck = array(1,2,3,4,5,6,7,8,9,10);
unset($deck[0]);
unset($deck[1]);
echo count($deck);
unset removes the elements from the array count should be 8 afterwards.
See it work: https://eval.in/163527
Edit:
...and remember arrays are 0 based so your first key unless otherwise defined will be 0. But the count() function will tell you the actual number of elements in the array. So $deck[count($deck)]; would be undefined.

This will echo size of array yourarray
<?php
echo(sizeof($yourarray));
?>

Store your array size using a count method such as count or sizeof store it in a variable and perform logical checks on it? i.e if().. etc . Your question is a tad bit broad.

I would recommend that you make use of the PHP count function.
echo count($yourArray);
Should do the trick.

Related

arrays. getting the 3rd item of this multi array

Please help. I want to print the price. I need to print the price only. Help me. Thanks
$x=array(array('itm_name'=>'Optimization','price'=>'100','desc'=>'Chuchu'));
It seems you are using a 2 dimensional array
have you tried
echo $x[0]['price']
note '0' is the first element of the 1st layer of the array
so this can be substituted with 'x' so can iterate through a list
additionally if you want to get the other items of the array then
echo $x[0]['itm_name']
i hope you have grasped the basic concept of multi-dimensional arrays
using this simple explanation
Use this:
$x[0]['price']
$x[0] means the first element of the outer array, and ['price'] gets the price element of the inner array.

Counting Array Returns One Digit Higher

I'm trying to count a php array.
I have my code successfully counting it, but the value is returning one digit higher than what my array is.
I have tried using -- when echoing my array, but that doesn't work.
Here is my code so far:
$quotes[0] = "Volvo";
$quotes[1] = "BMW";
$quotes[2] = "Toyota";
$quotesCount = count($quotes);
echo ($quotes[rand(0, 2)]);
echo $quotesCount--;
When it count's it returns "3" which makes sense because there are three items, but how do I subtract a number when it echos so that it reflects the the largest digit in the array?
What you tried with the echo $quotesCount--; is almost doing what you want it to. What you missed though is how the -- works. You can place it either infront of the variable or behind it - and that makes a difference.
To get the full version, read this: http://php.net/manual/en/language.operators.increment.php
But the short version is that you could potentially do this:
echo --$quotesCount;
Which will show you the value you want.
However this is still not really true - you are confusing array keys with the count of elements in an array.
If your array had non-sequential keys (1,3,5) for example, that code would return 2 - which is certainly not the highest key.
You can get a nice stepping stone to the key itself by using http://php.net/manual/en/function.array-keys.php - then you can reference the actual key itself by its order in the array.
You can use array_max($quotes) z this will return the highest key in the array.
Hey" you should array_max($array) in this case.
array_max is an array function which returns the highest value of an array.
That's it,
Keep Coding :)

Testing returned values for duplicates

I've got a method that returns a string with predefined length of random alpha numbers.
I just let it run until it comes across a duplicate and breaks out of the loop and display the amount of generations it took before a duplicate was generated.
The loop numbers will be in the millions, and I am wondering if this really is good and efficient of testing it?
You can use array_search
The function return the string and store it to an array.
Then use array_search to see if it is not FALSE and loop.
Put The generated strings into an array as a key before outputting them.
$array[$alpha_string] = (isset($array[$alpha_string])) ? $array[$alpha_string] + 1 : 1;
Then check which items have a count > 1.

when selecting random values from arrays, make sure two certain ones do not appear next to each other

I have an array with 18 values in it from which I select random values using $array[rand(0,17)]. I put these randomly selected values next to each other on the page. Within the array are 6 sets of values that I do not want to be put next to each other on the page. Is there any way that I can detect when the pairs are together and select new values because of that
warning: Do you know for sure that you won't get any degenerate cases where there are no possible orderings of the array? For example, if you won't allow the pairs [1,2] or [2,1] and the array you get is [1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2], the you're out of luck. There's no way to display the array in the way you want, and a method like I describe below will never terminate.
I would use shuffle($array) and then iterate through the shuffled array one item at a time, to find out whether any value is "incompatible" with the item before it. If so, just reshuffle the array and try again. You can't predict how many tries it will take to get a shuffled array that works, but the amount of time it takes should be negligible.
To detect whether two values are compatible, I'd suggest making an array that contains all incompatible pairs. For example, if you don't want to have the consecutive pairs 1 and 3 or 2 and 5, then your array would be:
$incompatible = array(
array(1,3),
array(2,5) );
Then you'd iterate over your shuffled array with something like:
for ($i=1; i<count($array)-1; i++;) {
$pair = $array[i, i+1]; // this is why the for loop only goes to the next-to-last item
if in_array($pair, $incompatible) {
// you had an incompatible pair in your shuffled array.
// break out of the for loop, re-sort your array, and try again.
}
}
// if you get here, there were no incompatible pairs
// so go ahead and print the shuffled array!
Or use with unset() for remove the keys, or use by Session, for next skip.

PHP - Not getting the element I expect from an array

I am paging through the elements of an array.
I get the total number of elements in the array with:
$total = count($myarray);
My paging function loads the current element on the page and provides "Previous" and "Next" links that have urls like:
http://myapp.com?page=34
If you click the link I grab that and load it onto the page by getting (I sanitize the $_GET, this is just for example):
$element = $myarray[$_GET['page']];
This should grab the element of the array with a key == $_GET['page'] and it does. However, the problem is that my total count of elements doesn't match some keys because while there are 100 elements in the array, certain numbers are missing so the 100th item actually has a key of 102.
How should I be doing this? Do I need to rewrite the keys to match the available number of elements? Some other method? Thanks for your input.
If you have gaps in the indices, you should reindex the array. You can do that before you generate the links, or probably easier on the receiving page:
$myarray = array_values($myarray);
$element = $myarray[$_GET['page']];
This would give you the 100th element, even if it previously had the key 102. (You could use a temporary array of course, if you need to retain the original indexing.)
you can use
$array = array_values($array);
How should I be doing this? Do I need
to rewrite the keys to match the
available number of elements? Some
other method?
No you don't need to worry about them not matching. Php arrays are associative containers, like dictionaries in other languages. If you define something at 98 and 100, 99 isn't sitting there in memory, the data structure behind the associative container only stores whats there. You're not wasting space by not "filling it up" up to count.
So the practice you describe is fine. If there is no page "99" nothing need show up in your array. It may be nice, however, to see that your array doesn't have anything for the 'page' parameter and display an error message.
But then why, when I access $total =
count($myarray); $myarray[$total]
where $total = 100 I do not get the
last element? I can put page=101 and
get one more record. I should not be
able to do this
Because count is counting how many things are in the array. If you have an array with only the even elements filled in, ie:
$myArray[0] = "This";
$myArray[2] = "is";
$myArray[4] = "even";
Here count($myArray) is 3. There's nothing in [1] or [3]. Maybe this is easier to see when you take numbers out of the equation. Arrays can have string indexes
$myArray = array();
$myArray["Hello"] = "A Bunch of";
$myArray["World"] = "words";
Here count($myArray) is 2.
In the first case, it wouldn't make sense to access $myArray[3] because nothing is there. Clearly in the second example, there's nothing at 2.

Categories