I don’t see why not use foreach, because when it comes to arrays with index it is a hand on the wheel. Foreach is native of PHP.
But let’s get down to business:
<?php
$lista = array(
array(
'id' => '100',
'name' => 'Sandra Shush',
'value' => 'a'
),
array(
'id' => '5465',
'name' => 'Stefanie Mcmohn',
'value' => 'a'
),
array(
'id' => '40489',
'name' => 'Michael',
'value' => 'b'
)
);
$ids = [];
for($i = 0; $i < count($lista); $i++) {
if( $lista[$i]['value'] == 'a' ) {
$ids[] = $lista[$i]['id'];
}
}
var_dump($ids);
Simplifying array syntax, and doing with foreach:
<?php
$lista = [
[
'id' => '100',
'name' => 'Sandra Shush',
'value' => 'a'
],
[
'id' => '5465',
'name' => 'Stefanie Mcmohn',
'value' => 'a'
],
[
'id' => '40489',
'name' => 'Michael',
'value' => 'b'
]
];
$ids = [];
foreach($lista as $item) {
if ( $item['value'] == 'a' ) {
$ids[] = $item['id'];
}
}
var_dump($ids);
You can also do with the array_map thus:
<?php
function teste($item) {
if($item['value'] == 'a') {
return $item['id'];
}
}
$lista = [
[
'id' => '100',
'name' => 'Sandra Shush',
'value' => 'a'
],
[
'id' => '5465',
'name' => 'Stefanie Mcmohn',
'value' => 'a'
],
[
'id' => '40489',
'name' => 'Michael',
'value' => 'b'
]
];
$b = array_map("teste", $lista);
echo '<pre>';
var_dump($b);
echo '</pre>';
The array_map will leave null those that do not enter the condition.
Thanks, the idea of not having to use the foreach was in case there was already something I write less without having to make a loop.
– Bruno Carvalho Silva Correa
But the idea of loops is exactly this.
– Matheus Picioli