0

This looks simple, but I just can't get it. For example, I have an array:

$array = array("new phone","old bag","new laptop","old PC");

I want to get the elements that start with "new",

RESULT: The elements that starts with "new" are:

"new phone" and "new laptop".

...so I have array with string elements and I want to obtain those elements that contains a specific string, doesn't matter if it starts the word as: "new phone", it can be also "phonenew", "phnewone", "asdkodsanewasd", I just look for "new" in elements and if I find it, I print all elements that contain it.

Very bad code:(one of codes)

$array = array("new phone","old bag","new laptop","old PC");
$x="new";
foreach($array as $x)
{
    echo $x;
}
S. Marius
  • 11
  • 2

1 Answers1

0

doesn't matter if it starts the word as: "new phone", it can be also "phonenew", "phnewone", "asdkodsanewasd"

So you can merely use a pretty simple regex:

function select_from_array($searched_word) {
    $selection = [];
    foreach ($array as $string) {
        if (preg_match('/' . $searched_word . '/', $string)) {
            $selection[] = $string;
        }
    }
    return $selection;
}
cFreed
  • 4,404
  • 1
  • 23
  • 33