0

There are way to do this in JavaScript, but in PHP they don't seem to work:

$myArray = array(
  array(
    "name" => "John Doe",
    "occupation" => "streamer"
  ),
  array(
    "name" => "Jena Doe",
    "occupation" => "delivery services"
  )
);

$newItem = array(
  "name" => "John Doe",
  "occupation" => "delivery services"
);

// now check if the name already exists
// to prevent from adding a duplicate clone of John Doe
if (!array_map(function($i){ if ($i['name'] === $newItem['name']) return true; else return false; }, $myArray)) {
  $myArray[] = $newItem;
}

Why am I getting Undefined variable: $newItem and how can I do this?

thednp
  • 4,401
  • 4
  • 33
  • 45
  • Because `$newItem` is outside of `function($i){`. https://stackoverflow.com/questions/42421492/access-variable-from-outside-function-php/42421507 – adampweb Mar 04 '21 at 08:45
  • Thanks, so I'm going to have to do a good old `foreach`. – thednp Mar 04 '21 at 08:48
  • 1
    You can import a variable from the parent scope into your callback function, using the `use` keyword. https://www.php.net/manual/en/functions.anonymous.php#example-181 – CBroe Mar 04 '21 at 08:51

1 Answers1

1

You could use a simple test using in_array to see if the new array contains the duplicate name before adding?

$src = array(
    array(
        "name"          => "John Doe",
        "occupation"    => "streamer"
    ),
    array(
        "name"          => "Jena Doe",
        "occupation"    => "delivery services"
    )
);
$new=array(
    "name"              => "John Doe",
    "occupation"        => "delivery services"
);


if( !in_array( $new['name'], array_values( array_column( $src, 'name' ) ) ) ){
    $src[]=$new;
}
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46