Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to array with Reference

I am trying to build a function for easier array manipulation in my project.

I want to do it by passing reference. Hoping to be more productive and resource-saving way.

function add_element ($element=array(),&$data) {
    if(!empty($data)) {
      $data += $element;
    }
    return true;
  }

// $element can be array('one','two') or array('color'=>'blue','type'=>'card')

I am not experienced with references, thanks for any tip.

like image 841
YahyaE Avatar asked Jan 31 '26 02:01

YahyaE


1 Answers

I believe that this will have the effect that you're looking for. We are passing in the original array as the reference and it adds whatever data you pass to it to the original array.

function add_element (&$original_array = array(), $data) {

  // Cast an array if it isn't already
  !is_array($data) ? (array)$data : null;

  if(!empty($data)) {
    $original_array = $original_array + $data;
  }
  return true;
}

$names_array = array("first_name" => "bob");
$data_to_add = array("second_name" => "fred");

// Add new variable
add_element($names_array, $data_to_add);

// Show the contents
print_r($names_array);

See it live here: http://www.tehplayground.com/#DJXofIeQK

However, I have just taken what you posted as a starting point there. The above is basically the same as the following, which requires no special function:

$names_array = array("first_name" => "bob");
$data_to_add = array("second_name" => "fred");

// Add new variable
$names_array = $names_array + $data_to_add;

// Show the contents
print_r($names_array);

See it here: http://www.tehplayground.com/#PAbhOHaPT

like image 72
Luke Avatar answered Feb 01 '26 16:02

Luke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!