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?
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.
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.
The array_chunk() function splits an array into chunks of new arrays.
#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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With