Define foreach inside a method to avoid repetition

You could envisage using a trait.

In short, a trait allows you to: reuse sets of methods freely in several independent classes living in different class hierarchies. (source: the manual).

An example to help better understand the concept:

  1. Define a trait, call it e.g. Iterate, here it has one function loop(array $arr)
  2. Inside the class where you want to use function loop, use: use Iterate
  3. Now, as you can see, we can invoke the function: $this->loop() inside class Test

.

<?php

trait Iterate
{
    public function loop(array $arr)
    {
        foreach ($arr as $key => $value) {
            echo 'key : ' . $key;
            echo '<br />';
            echo 'value : ' . $value;
            echo '<br />';
        }
    }
}

class Test
{
    use Iterate;

    public function __construct($arr)
    {
        $this->loop($arr);
    }
}
$arr = [1, 2, 3];
$test = new Test($arr);

Output:

key : 0
value : 1
key : 1
value : 2
key : 2
value : 3

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top