PHP - Not getting the element I expect from an array - php

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.

Related

Push or Merge data into existing Array

When working with existing code, it takes one array and places it into another in the fashion shown below.
I believe the empty brackets are the same thing as simply pushing it and appending it to the first available index.
$g['DATA'][] = $p;
After this is done, I have my own array that I would like to append to this as well. I tried using array_merge() with $g['DATA'][]as a parameter, but this is invalid for obvious reasons.
My only thought is to create a foreach loop counter so I can figure out the actual index it created, however I have to assume there is some cleaner way to do this?
Just simply use the count() of your $g["DATA"] array as index and then you can merge it like this:
$g['DATA'][count($g["DATA"])-1] = array_merge($g['DATA'][count($g["DATA"])-1], $ownArray);
//^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^
// -1 Because an array is based index 0 -> means count() - 1 = last key

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 :)

PHP Cycle through array. Move the first element to the last

Just thought I would like to share this should someone find a use for it.
Basically I needed a list of HTML colors to loop / cycle through. So I need to remove the first element of the array, place it at the end and then get the current HTML color.
Given the following array:
$colors = array(
"#2265fa", "#b61d1e", "#53b822", "#a9d81c", "#d6e9f5", "#43cc7d", "#e3159a",
"#80c85e", "#17b303", "#989240", "#014c07", "#d265f3", "#22bbb9", "#6c69a9",
"#7ea13a", "#0dcea2", "#99c27d", "#41405b", "#731801"
);
So this is what I came up with. Sure there will be hundreds of ways to do this. This is my take on it.
# Array_shift returns the value it takes off the beginning of the array.
# And I merely append this to the end of the array
$colors[] = array_shift($colors);
# Using current I am able to get the current first element of the array back
echo current($colors);
In this case it would be "#b61d1e" that is the current index for the array. May you find this useful somewhere.

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.

Alternative to array_shift function

Ok, I need keys to be preserved within this array and I just want to shift the 1st element from this array. Actually I know that the first key of this array will always be 1 when I do this:
// Sort it by 1st group and 1st layout.
ksort($disabled_sections);
foreach($disabled_sections as &$grouplayout)
ksort($grouplayout);
Basically I'd rather not have to ksort it in order to grab this array where the key = 1. And, honestly, I'm not a big fan of array_shift, it just takes to long IMO. Is there another way. Perhaps a way to extract the entire array where $disabled_sections[1] is found without having to do a foreach and sorting it, and array_shift. I just wanna add $disabled[1] to a different array and remove it from this array altogether. While keeping both arrays keys structured the way they are. Technically, it would even be fine to do this:
$array = array();
$array = $disabled_sections[1];
But it needs to remove it from $disabled_sections. Can I use something like this approach...
$array = array();
$array = $disabled_sections[1];
$disabled_sections -= $disabled_sections[1];
Is something like the above even possible??
Thanks.
Despite there being an accepted answer to this; in case someone else stumbles across this, a way to unset the first element of an array (regardless of its key, or the order of its keys) without using array_shift is:
reset($array); // sets internal array pointer to start
unset($array[key($array)]); // key() returns key of current array element
Though I'm fairly convinced that's what array_shift does internally (so I imagine there would be no performance gain to this), excepting an additional return of the value retrieved:
$element = reset($array); // also returns element
unset($array[key($array)]);
return $element;
Just for completion's sake.
While there's no -= operator in that fashion, you can use unset to remove that element from an array:
unset(disabled_sections[1]);
But that's just implementing your own version of shift. I do wonder under what situation you're finding array_shift() to be 'slow' and how you're testing said slowness.
Numeric arrays are sorted numerical by default - no ksort is required. Maybe you should try something like
while($array = array_shift($group_of_arrays)) {
// ... do stuff
}
If you are not concerned about the order in which you pull elements out of the array, you can use "array_pop" instead of "array_shift". Since "array_pop" takes the elements off of the end of the array, no reindexing is required and performance increases dramatically. In testing with an array of about 80,000 entries I am seeing about a 90% decrease in processing time with "array_pop".

Categories