If I understand correctly the purpose is to transfer from the input array all elements that have the same prefix characterized by an expression followed by an underscore .
So, I propose the scheme below:
$filtered = array();
array_walk(
$arr,
function( $current, $offset ) use( $arr, &$filtered ) {
preg_match( '/(\w+_\d+)/', $offset, $matches );
if( count( $matches ) > 0 && array_key_exists( $matches[ 1 ], $arr ) ) {
$filtered[ $matches[ 1 ] ] = $current;
}
}
);
Using the input array with the same name you have today ( $ arr ) the resulting array $ filtered will have the following values:
array(
'numero_1' => '1',
'rua_1' => 'rua 1',
'numero_2' => '2',
'rua_2' => 'rua 2'
)
Your second question can be answered simply by computing the difference between the two arrays, original and filtered:
$diff = array_diff_assoc( $arr, $filtered );
The $ diff array has the following values:
array(
'id' => '147',
'nome' => 'João',
'email' => '[email protected]',
'data_nascimento' => '05/01/1987',
'submit' => 'Salvar'
)
This approach has the following advantages:
- Do not depend on a fixed expression, that is, as long as all similarities follow the same format prefix_number , it will work in the entire array.
- It is fast, because it dispenses calculations, complex conditions and nested loops. So even if large arrays are bad enough for your Application, this procedure is not going to be your bottleneck.