Message: Undefined offset |
[eluser]sovandy[/eluser]
Dear all, I have an error while I am comparing array() elements. let you see my code: Code: for($i=0;$i<count($get_book_id);$i++) The error: <i> A PHP Error was encountered Severity: Notice Message: Undefined offset: 18 Filename: models/book.php Line Number: 48 </i>
[eluser]Dam1an[/eluser]
I'm going to assume line 48 is the if statement? You get the undefined offset on the last iteration of the loop where you're comparing the last element, to the last element + 1, which obviously doesn't exist. The best way to rewrite this is to start the loop off at 1, and compare to the previous item, so instead of comparing 0 and 1, you compare 1 and 0 Another suggestion is to not have the count in the condition for the for loop as it gets called every time, call it once and assign it to a variable and use that instead
[eluser]sovandy[/eluser]
But after I changed it, I lost one value: I have 5 elements in my array(). Please see Code: for($i=1;$i<$mycount;$i++)
[eluser]Dam1an[/eluser]
What do you mean by 'lost one value'? If you have say 10 items in an array, and you're comparing each one to the previous/next one, there will only be 9 comparisions, so even if each comparison gives you true, you will still only add 9 items It would also be the same as if you done Code: for($i = 0; i < $count - 1; i++) Also, on a side note, I think $get_book_id is a horrible name for an array lol
[eluser]Evil Wizard[/eluser]
Code: for($i=1;$i<$mycount;$i++) Code: $get_final_array = array_unique($get_book_id);
[eluser]sovandy[/eluser]
Yes, thank you very much. I can do it now. Before I get your help, I try many times and use many loop. I can reduce it a lots. Best regards, <i>Sovandy</i>
[eluser]Dam1an[/eluser]
[quote author="Evil Wizard" date="1246373661"] It looks as though you want to reduce the array to unique element values [/quote] Thats what I initially thought s/he was trying to do, but was only comparing to the next/previous item, so thought it must have been after something else |
Welcome Guest, Not a member yet? Register Sign In |