-2

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • You want get car from $array1 and push it into $array2 ? – Sachin Dec 19 '18 at 07:36
  • yes, that's right. –  Dec 19 '18 at 07:37
  • Should it be removed from the original array? – Nigel Ren Dec 19 '18 at 07:39
  • We're a community designed to help developers solve problems that they cannot solve on their own. It is also our responsibility to enforce the rules by ensuring that people who need help have done their own research. Your question could clearly be solved by making a simple google search. Stackoverflow should not be the first place you come to solve your problems because it is very likely that someone has faced a similar issue. We don't expect you to know every thing but we do expect you to try and help yourself first. https://stackoverflow.com/help/how-to-ask You can check out the help center. – chinloyal Dec 19 '18 at 11:54

3 Answers3

0

You can push $array1 item car into $array2 as like below

$array2 = array();
$array1 = ["banana","car","carrot"];  

array_push($array2, $array1[1]);

print_r($array2); /* OutPut Array ( [0] => car ) */ 

As you know $array1[1] has value is car so it will push it into $array2 by suing php built-in function array_push()

Ayaz Ali Shah
  • 3,453
  • 9
  • 36
  • 68
  • I am trying to do it not by number but by name. is it possible? –  Dec 19 '18 at 07:43
  • @Barbie since this is not an associative array so you can't use key as string because there is not. So you will have to use `index` – Ayaz Ali Shah Dec 19 '18 at 07:44
0

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',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • I was very surprised to see the flurry of downvotes -- I cannot confidently state the reason. The most you can do is make sure that you clearly thoroughly explain your questions. – mickmackusa Dec 19 '18 at 07:57
-2

Hope this will help you.

$array1 = ["banana","car","carrot"];  
$array2 = array_slice($array1, 1, 1);
unset($array1[1]);
Karthik Sekar
  • 625
  • 4
  • 7