i read information out of a MSSQL database and save this into arrays with a length of 2000.
When i echo the entries i get the length of these arrays in the first entry (e.g. amount[0] = 2000).
Does php do this by default or is there no default value?
(The cells in my database which go into these arrays are empty in the first entry)
Thank You
If i understand your question very well. PHP uses a function called count() to determine the length of an array ,you can do somethiing like this,
$x = [12,11,334,56,788,999,45,56,23];
$y = count($x);
then change the value of the first array element like this,
$x[0] = $y;
So whenever you call $x[0] you will get the length of the array.
Related
At the moment i try to create a function in php which simply reads an int value of a field of an array and compares it to a max value.
If this max value is reached, it shall set the value of the field to zero, jump to the next field in the array and increase the int value stored inside.
If this value also reached the max value do the same as above.
If the above condition isnĀ“t true it shall just increase the stored value in the array.
My Code looks like this:
if($sign_counter[0] === (count($pw_signs) - 1)){
$counter = 0;
while($sign_counter[$counter] === (count($pw_signs) - 1)){
$sign_counter[$counter] = "0";
$counter++;
}
$sign_counter[$counter]++;
}
else{
$sign_counter[0]++;
}
I allready tested this part of the function several times with different values on my website and browser. I also checked if the values were stored correctly in the array and inside needed variables.
Thats how my array looks like:
$sign_counter = array("38", "2");
For example:
$sign_counter array to store int values
(count($pw_signs) - 1) always equals 38 (because there are 39 fields in the counted array)
$counter used to determine the field position inside the array
Now if i store the value "38" in the first field and "2" in the second field of the array the code should detect, that the max value is reached in the first field, set the value of the field to 0, then jump to the next field and increase its value by 1.
Instead of what i want to achieve the code just increases the value of the first field of the array.
It looks like the while loop just ignores it's own condition but the values itself don't seem to be the problem.
I don't really get why the while loop behaves like this.
Do i completly miss something here?
Would appreciate any help.
Greetings Sleepy
The problem is that you're storing the values as strings, not numbers, and you're using the === operator, which doesn't perform type coercion between different types. count($pw_signs) - 1 will always be a number, not a string, all the === tests will fail.
Get rid of the quotes around all the numbers and it should work as desired. And if the source of the values is external, convert them to numbers with intval() before storing into the array.
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 :)
I am trying to access certain subarrays of an array depending on a sha1 code saved in the subarray.
I have the following code working for me:
//I take a sha1 string of 40chars from GET
if(isset($_REQUEST['sha1'])){
//then I iterate through the array and check if the subarrays sha1 matches
for($i = 0; $i < count($scomplaints); $i++) {
if($scomplaints[$i]['sha1'] == $_REQUEST['sha1']){
//once a match is found I delete the match...
unset($scomplaints[$i]);
//... reserialize the array and update it in the database
$new_c = serialize($scomplaints);
// ( add new array to database )
break;
}
}
}
Pretty straight forward. Only problem is: In some random cases the loop doesnt read the sha1 value of the subarray. Instead it reads an empty string from the array.
But when i var_dump the array the sha1 code is clearly saved in the array and also identical to the one I get from GET (I did a by hand comparison).
I can't figure out what the problem is, maybe some encoding error? Maybe one of you guys can help me with this?
Thanks for all advice.
I got it solved. The issue was the array not being reindexed by unset($array). Once I reindex it with array_values($array) it works again.
In the PHP documentation it says:
Do not use return-by-reference to increase performance. The engine
will automatically optimize this on its own.
I wish to return a reference to an array (which is a property of my class). How does PHP optimize this, because the array is not an object?
If the array has 1 billion entries, won't I get two arrays with 1 billion entries stored in memory if I don't pass it by reference?
PHP uses copy on write. That means that if you pass the huge array as a function parameter and only read from it (such as a foreach), you won't be writing to it so it doesn't need to make a copy.
$count = count($huge_array); // read the reference at the bottom
for($i = 0; $i < $count $i++) {
$value = 2*$huge_array[$i]/15;
if($value > 3)
$sub_array []= $value;
}
The $subarray which should be smaller (it is a subset of the huge array), will contain only the needed (changed) data.
If you do not intend on changing the values of the original $huge_array it will never get copied so no extra memory is used.
If you intend on changing the original values of the array, you need to pass it by reference.
If you intend on making and returning an altered version of the original array then you do need the extra memory PHP is allocating for you.
If you intend on making and returning an altered smaller subset of the original array then you will create a new empty array into which you will copy some of data from the huge array and should be careful not to overwrite values in the $huge_array, so you'll avoid writing from $huge_array and emphasise on reading from it.
This link explains that PHP was optimised for pass by value use cases.
Copy on write only works if the variable isn't a reference being passed to a function expecting a value, if it is, passing it around triggers a copy.
That makes PHP native functions that expected an argument to be passed by value and received a referenced variable copy the value of the reference.
function foo(&$data) {
for ($i = 0; $i < strlen($data); $i++) {
do_something($data{$i});
}
}
$string = "... looooong string with lots of data .....";
foo(string);
Executing strlen in C would imply iterating over the entire string to count it. In PHP strings have an attached length value. So strlen returns the value read from there (fast).
But if you give it a referenced variable it will have to copy it before reading it's length so it will iterate over the value to copy it into it's argument list, read and return the length (and subsequently release the memory for the freshly copied string).
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.