Search code examples
phparrayssearcharray-push

How to push a found array item into another array?


I have an array. But trying to separate items. For example:

$array1 = ["banana","car","carrot"];  

trying to push car into another array which is $array2

$push = array_push($array1, "car") = $array2;

I try to find array_push usage for this but the documentation is all about. sending new item to array. Not array to array. Is this possible with array_push or need to use something else?

I need to search for the value car in $array1, push it into $array2 and remove it from $array1.


Solution

  • Here is a flexible solution that allows you to search by "car", then IF it exists, it will be pushed into the second array and omitted from the first.

    Code: (Demo)

    $array1 = ["banana","car","carrot"];  
    $needle = "car";
    if (($index = array_search($needle, $array1)) !== false) {
        $array2[] = $array1[$index];
        unset($array1[$index]);
    }
    
    var_export($array1);
    echo "\n---\n";
    var_export($array2);
    

    Output:

    array (
      0 => 'banana',
      2 => 'carrot',
    )
    ---
    array (
      0 => 'car',
    )