PHP splitting array into two arrays based on value
This should do the trick:
$myArray = array('item1', 'item2hidden', 'item3', 'item4', 'item5hidden');
$secondaryArray = array();
foreach ($myArray as $key => $value) {
if (strpos($value, "hidden") !== false) {
$secondaryArray[] = $value;
unset($myArray[$key]);
}
}
It moves all the entries that contain "hidden" from the $myArray
to $secondaryArray
.
Note: It's case sensitive
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);