Search code examples
phparraysclass-methodarray-mergeclass-properties

Accumulate strings and array values into an array as a class property via method


I have a class with method add() that accepts strings and arrays. I need to have an array with all users, but I cannot seem to get it. All I get is multiple arrays with all users. How could I merge those arrays into one?

class Users {

    function add($stringOrArray) {
        $arr = array();
        if(is_array($stringOrArray)) {
            $arr = $stringOrArray;
            
        } else if(is_string($stringOrArray)) {
            $arr[] = $stringOrArray;
            
        } else {
          echo('errrrror');
        }
        print_r($arr);
        
    }

When I use this test:

public function testOne() {
    $users = new Users();
    $users->add('Terrell Irving');
    $users->add('Magdalen Sara Tanner');
    $users->add('Chad Niles');
    $users->add(['Mervin Spearing', 'Dean Willoughby', 'David Prescott']);

This is what I get, multiple arrays but I need one array.

Array
(
    [0] => Terrell Irving
)
Array
(
    [0] => Magdalen Sara Tanner
)
Array
(
    [0] => Chad Niles
)
Array
(
    [0] => Mervin Spearing
    [1] => Dean Willoughby
    [2] => David Prescott
)

Solution

  • You can cut a lot of unnecessary bloat from your method.

    1. You can cast ALL incoming data to array type explicitly. This will convert a string into an array containing a single element. If the variable is already an array, nothing will change about the value.

    2. Use the spread operator (...) to perform a variadic push into the class property.

    Code: (Demo)

    class Users
    {
        public $listOfUsers = [];
    
        function add($stringOrArray): void
        {
            array_push($this->listOfUsers, ...(array)$stringOrArray);
        }
    }
    
    $users = new Users;
    $users->add('Terrell Irving');
    $users->add(['Magdalen Sara Tanner', 'Chad Niles']);
    $users->add(['Mervin Spearing']);
    var_export($users->listOfUsers);
    

    Output:

    array (
      0 => 'Terrell Irving',
      1 => 'Magdalen Sara Tanner',
      2 => 'Chad Niles',
      3 => 'Mervin Spearing',
    )