The SPL extension allows us to use objects as array. One way to do this is to use the class predefined ArrayObject. Another way is to implement an interface ArrayAccess to access our data as if they were an array. An example of this
class MyArray implements ArrayAccess {
private $data;
public function __construct($array = array())
{
$this->data = $array;
}
public function offsetGet($key)
{
return $this->data[$key];
}
public function offsetSet($key, $value)
{
return $this->data[$key] = $value;
}
public function offsetExists($key)
{
return isset($this->data[$key]);
}
public function offsetUnset($key)
{
unset($this->data[$key]);
}
public function avg()
{
if (count($this->data) > 0)
{
return array_sum($this->data) / count($this->data);
}
}
}
//echo 0xFACEB00C >> 2;
$array = new MyArray(array(1, 2, 3, 4));
echo (int)isset($array[0]);
echo $array[0];
unset($array[1]);
echo (int)isset($array[1]); //throw an ugly notice
echo $array[1];
$array[1] = 4;
echo (int)isset($array[1]);
echo $array[1];
echo $array->avg();
Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts
Thursday, November 22, 2007
Sunday, September 23, 2007
Storing array elements in a variable
The other day, called the attention to read that is slower to accede to an array element than to a variable. I decided to prove whatever is the difference, and if it is worth the trouble. My conclusion is that the difference exists and if is called more than 10 times to the same index, can be worth the trouble to create a variable for that, but is also only recommendable to do it within a function, in a “scope” so that it is not all along in the memory.
View example
View example
Sunday, September 16, 2007
Iterate over array
Perhaps it sounds repeated to the for - while post, but now instead of executing a code N times, I want to run all the positions of an array. Which is the most advisable way?
In the first place, we have the optimized for.
On the other hand, we can use foreach, that exactly crosses the array of data.
A last alternative is to be crossing the array using its internal pointer.
In this case, the best alternative is foreach, specially dedicated for this.
View example
In the first place, we have the optimized for.
On the other hand, we can use foreach, that exactly crosses the array of data.
A last alternative is to be crossing the array using its internal pointer.
In this case, the best alternative is foreach, specially dedicated for this.
View example
Subscribe to:
Posts (Atom)