Page 1 of 1

Fixing some methods of my list implementation

Posted: Mon Apr 05, 2010 3:51 pm
by Myamo
Hello,

I've recently implemented a class which represents a list. Internally, the list is an array.
Most of its methods work correctly. Only two are making me trouble.

The first method is the contains method. It checks if the list contains the element given to it through a parameter.
It returns true, if the list contains the element.
Here is the method:

Code: Select all

	public function contains($element){
		for($i=0;$i<$this->size();$i++){
			if($element == $this->list[i]){
				return true;
			}
		}
	}
The size method works correctly. $this->list is the array which represents the list.
I use this on a site where I type in the element in an input field and then post it.

Then I call following piece of code:

Code: Select all

if($l->contains($_POST['Element'])){
						echo 'Element is in the list';
					}else{
						echo 'Element is not in the list';
					}
However, this always executed the else part so far, even when I inputted an element which is in the list. Only when I left the input field empty the if part was executed.

Any idea on what is wrong?

Re: Fixing some methods of my list implementation

Posted: Mon Apr 05, 2010 4:02 pm
by AbraCadaver
First off, you forgot the $ before the i in , secondly, I would do this:

Code: Select all

public function contains($element){
    return in_array($element, $this->list);
}

Re: Fixing some methods of my list implementation

Posted: Mon Apr 05, 2010 5:35 pm
by requinix
AbraCadaver wrote:secondly, I would do this:
For that matter, why implement a List class when PHP already has the functionality for every operation?
Homework exercise?

Re: Fixing some methods of my list implementation

Posted: Mon Apr 05, 2010 6:29 pm
by AbraCadaver
tasairis wrote:
AbraCadaver wrote:secondly, I would do this:
For that matter, why implement a List class when PHP already has the functionality for every operation?
Homework exercise?
+1

I was going to say why not just use in_array() instead of making it a method, but some people like to build their own class and wrap some functions. But yes, maybe it's homework :-)