Reputation: 1496
I want to change the value of an array without loop-
Example code:
<?php
//current array
$ids = array('1113_1', '1156_6', '1342_16', '1132_3', '1165_2');
//result should be looks like this
$ids = array('1113', '1156', '1342', '1132', '1165');
?>
is it possible to do it without any loop?
Upvotes: 0
Views: 1135
Reputation: 145472
Instead of the shown string/array function workarounds, you can also just use a PHP built-in to filter the arrays:
$ids = array('1113_1', '1156_6', '1342_16', '1132_3', '1165_2');
$ids = array_map("intval", $ids);
This converts each entry into an integer, which is sufficient in this case to get:
Array
(
[0] => 1113
[1] => 1156
[2] => 1342
[3] => 1132
[4] => 1165
)
Upvotes: 3
Reputation: 360562
array_map()
, but internally it'd still be using a loop.
function $mycallback($a) {
... process $a
return $fixed_value;
}
$fixed_array = array_map('mycallback', $bad_array);
Upvotes: 1
Reputation: 28906
Possible? Yes:
$ids[0] = substr($ids[0], 0, -2);
$ids[1] = substr($ids[1], 0, -2);
$ids[2] = substr($ids[2], 0, -3);
$ids[3] = substr($ids[3], 0, -2);
$ids[4] = substr($ids[4], 0, -2);
But why do you want to avoid using a loop in this case?
Upvotes: 1
Reputation: 146302
Try this using array_map()
:
<?php
function remove_end($n)
{
list($front) = explode("_", $n);
return $front;
}
$a = array('1113_1', '1156_6', '1342_16', '1132_3', '1165_2');
$a = array_map("remove_end", $a);
print_r($a);
?>
Demo: http://codepad.org/iGJ3cJW2
Upvotes: 2