Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP splitting array into two arrays based on value

I have a PHP array that I am trying to split into 2 different arrays. I am trying to pull out any values that contain the word "hidden". So one array would contain all the values that do not contain the word "hidden". The other array would contain all the values that do contain the word "hidden". I just can't figure out how to do it though.

The original array is coming from a form post that contains keys and values from a bunch of check boxes and hidden inputs. so the actual post value looks something like this:

Group1 => Array([0] => item1,[1] => item2hidden,[2] => item3,[3] => item4,[4] => item5hidden)

so to simplify it:

$myArray = Array(item1, item2hidden, item3, item4, item5hidden)

final output

$arr1 = (item1, item3, item4)
$arr2 = (item2hidden, item5hidden)

Anyone know how to do something like this?

like image 740
Austin Avatar asked Nov 20 '13 14:11

Austin


People also ask

How do you divide an array into two parts?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

Which construct can be used to split an array into a number of values?

An array can be split into the number of chunks. A built-in function array_chunk() can be used to split the array into multiple arrays with a defined number of elements.

What is Array_chunk?

The array_chunk() function splits an array into chunks of new arrays.

How can I get array values and keys into separate arrays in PHP?

#1 Using array_slice function to split PHP arrays array_slice() returns the sequence of elements from the array as specified by the offset and length parameters. $offset – The position in the array. $preserve_keys – Output the associative array with integer keys intact.


1 Answers

You can use array_filter() function:

$myArray = array('item1', 'item2hidden', 'item3', 'item4', 'item5hidden');

$arr1 = array_filter($myArray, function($v) { return strpos($v, 'hidden') === false; });
$arr2 = array_diff($myArray, $arr1);

Demo

like image 73
Glavić Avatar answered Oct 05 '22 09:10

Glavić