Home > database >  How to check an array for a value and push that value to a different array?
How to check an array for a value and push that value to a different array?

Time:10-12

What I want the code below to do is loop through the $check_query array, find all the values that contain the word standard and push them into an array. I'd like to also do this for the strings that contain upgrade. Example $range_array should return ['standard-186', 'standard-184];

    $check_query = ['standard-186', 'upgrade-186', 'standard-184', 'upgrade-184'];
    $range_array = [];
    $spec_array = [];

    foreach($check_query as $value) {

        if (in_array("standard", $value)) {
            array_push($range_array, $value);
        }
        elseif (in_array("upgrade", $value)) {
            array_push($spec_array, $value);
        } else {
            // Nothing
        }
    }
    
    echo $range_array;
    echo $spec_array;

CodePudding user response:

This can be done in one line using array_filter()

<?php

$check_query = ['standard-186', 'upgrade-186', 'standard-184', 'upgrade-184'];

$value = "standard";

$range_array = array_filter($check_query, function($a) use($value){return (stripos($a, $value)!==false);});
print_r($res);

Output

Array ( [0] => standard-186 [2] => standard-184 ) 

For $spec_array do the same thing with a different value for $value.

For PHP 8 you can use str_contains() instead of stripos():

$res = array_filter($check_query, function($a) use($value){return str_contains($a, $value);});
print_r($res);

CodePudding user response:

In the loop, $value contains a string, so you have to check if your string is a part of that string.

$check_query = ['standard-186', 'upgrade-186', 'standard-184', 'upgrade-184'];
$range_array = [];
$spec_array = [];

foreach($check_query as $value) {

    if (strpos($value,"standard") !== false) {
        array_push($range_array, $value);
    }
    elseif (strpos($value,"upgrade") !== false) {
        array_push($spec_array, $value);
    } else {
        // Nothing
    }
}

Outputs:

enter image description here

enter image description here

  • Related