hd.
hd.

Reputation: 18316

Get a sub array with a pattern in php

Consider this array in PHP:

$list = array('apple','orange','alpha','bib','son','green','odd','soap');

How can i get a sub array of elements start with letter 'a' or 's' ?

Upvotes: 1

Views: 526

Answers (6)

Igor Hrcek
Igor Hrcek

Reputation: 735

This is one way of doing it:

    $list = array('apple','orange','alpha','bib','son','green','odd','soap');


$a = array();
$s = array();
for ($i = 0; $i < count($list); $i++)
{
    if (substr($list[$i], 0, 1) == "s")
    {
        $s[$i] = $list[$i];
    }
    else if (substr($list[$i], 0, 1) == "a")
    {
        $a[$i] = $list[$i];
    }
}

Upvotes: 0

Trieu Nguyen
Trieu Nguyen

Reputation: 51

<?php

$list = array('apple','orange','alpha','bib','son','green','odd','soap');

$tmp_arr = array(); foreach ($list as $t) { if (substr($t, 0, 1) == 'a' || substr($t, 0, 1) == 's') { $tmp_arr[] = $t; } }

print_r($tmp_arr);

?>

//output: Array ( [0] => apple [1] => alpha [2] => son [3] => soap )

Upvotes: 0

UltraInstinct
UltraInstinct

Reputation: 44444

Check out array_filter here: http://www.php.net/manual/en/function.array-filter.php

$list = array_filter($list, function ($a) { return $a[0] == 'a' || $a[0] == 's'; });

Upvotes: 4

benqus
benqus

Reputation: 1149

for ($i =0; $i < count($list); $i++) {
    if (substr($list[i], 1) == "a" || substr($list[i], 1) == "s") {
        //put it in an other array
    }
}

Upvotes: 0

Hammerite
Hammerite

Reputation: 22340

$sublist = array();
for ($i = 0; $i < count($list); $i++) {
    if ($list[$i][0] == 'a' or $list[$i][0] == 's') {
        $sublist[] = $list[$i];
    }
}

Upvotes: 1

user187291
user187291

Reputation: 53940

http://php.net/manual/en/function.preg-grep.php

$items = preg_grep('~^[as]~', $list);

Upvotes: 7

Related Questions