1

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' ?

6 Answers 6

7

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

$items = preg_grep('~^[as]~', $list);
Sign up to request clarification or add additional context in comments.

2 Comments

$a = preg_grep('#^a|s#', array_map('strtolower', $list)); Just in case you have mixed case (make apple Apple in your test). +1 for posting a proper PHP array we can just copy and use. Thoughtful.
Ah, well it seems to, then again this is better $a = preg_grep('#^a|s#i', $list); <-use the i regex switch
4

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'; });

Comments

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

2 Comments

$list[$i][0] <-- can you do that in PHP? =O Never thought of that one before... =] Nice! =]
@benqus: Yes, PHP allows you to give a string offset using the array-offset notation. Like any PHP operation involving strings, it won't behave well if you have a string in a multi-byte character set.
0
for ($i =0; $i < count($list); $i++) {
    if (substr($list[i], 1) == "a" || substr($list[i], 1) == "s") {
        //put it in an other array
    }
}

Comments

0
<?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 )

1 Comment

This poorly formatted answer is missing its explanation.
0

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];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.