Reputation: 18316
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
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
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
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
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
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
Reputation: 53940
http://php.net/manual/en/function.preg-grep.php
$items = preg_grep('~^[as]~', $list);
Upvotes: 7