skip to Main Content

Need to split single array to multiple array using key word.
This is the input array.

Array
(
    [0] => "handrail-18"
    [1] => "handrail-17"
    [2] => "handrail-16"
    [3] => "safetyLine-26"
    [4] => "safetyLine-25"
)

I have try this below code but still I didn’t getting proper solution

 $components_nodetype = array();
foreach($components_parenttype as $item) {
    if (isset($item) && $item === "safetyLine") {
        $components_nodetype[] = $item;
    }
}

I need output like below. This array based on handrail and safetyLine it should get separate by two array

$Array1 = Array
(
    [0] => "handrail-18"
    [1] => "handrail-17"
    [2] => "handrail-16"
)
$Array2 = Array
(   
    [0] => "safetyLine-26"
    [1] => "safetyLine-25"
)

2

Answers


  1. You can solve this by iterating through the array and checking if each element contains the keyword ("handrail" or "safetyLine") by using strpos. If it does, you can add it to the corresponding output array.

    $handrailArray = array();
    $safetyLineArray = array();
    
    foreach ($inputArray as $item) {
        if (strpos($item, "handrail") !== false) {
            $handrailArray[] = $item;
        } elseif (strpos($item, "safetyLine") !== false) {
            $safetyLineArray[] = $item;
        }
    }
    
    Login or Signup to reply.
  2. It’s more proper to save then in a array aggregated by the key, instead of each an array.

    $input = array
    (
        "handrail-18",
        "handrail-17",
        "handrail-16",
        "safetyLine-26",
        "safetyLine-25"
    );
    
    $output = [];
    foreach($input as $item){
        $key = explode('-', $item)[0];
        $output[$key][] = $item;
        // $$key[] = $item; // if you want to save then in seperate variables, but this not the recommended way;
    }
    
    var_dump($output);
    

    And the output:

    array(2) {
      ["handrail"]=>
      array(3) {
        [0]=>
        string(11) "handrail-18"
        [1]=>
        string(11) "handrail-17"
        [2]=>
        string(11) "handrail-16"
      }
      ["safetyLine"]=>
      array(2) {
        [0]=>
        string(13) "safetyLine-26"
        [1]=>
        string(13) "safetyLine-25"
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search