4

I have an array in the below format.

array (
0 => 
array (
'safe_route' => 'yes',
'route_name' => 'route_1',
'route_risk_score' => '2.5'),
 1 =>
array (
'safe_route' => 'no',
'route_name' => 'route_2',
'route_risk_score' => '3.5'),
 2 =>
array (
'safe_route' => 'no',
'route_name' => 'route_3',
'route_risk_score' => '4.5')
)

i need to loop it and remove the key 'route_risk_score' with its value inside all arrays. How this can be done in php. Am new to php.Help would be appreciated

0

2 Answers 2

8

To delete element in original array, use a reference to each element:

// see this & in front of `$item`? 
// It means that `$item` is a reference to element in original array 
// and unset will remove key in element of original array, not in copy
foreach($array as &$item) {          
    unset($item['route_risk_score']);
}
Sign up to request clarification or add additional context in comments.

Comments

6
$data = array(
0 =>array(
    'safe_route' => 'yes',
    'route_name' => 'route_1',
    'route_risk_score' => '2.5'),
1 =>array(
    'safe_route' => 'no',
    'route_name' => 'route_2',
    'route_risk_score' => '3.5'),
2 =>array(
    'safe_route' => 'no',
    'route_name' => 'route_3',
    'route_risk_score' => '4.5')
);
$count = count($data);
for ($i = 0; $i < count($data); $i++) {
     unset($data[$i]['route_risk_score']);
}
echo'<pre>';print_r($data);die;
output :
Array
(
[0] => Array
    (
        [safe_route] => yes
        [route_name] => route_1
    )

[1] => Array
    (
        [safe_route] => no
        [route_name] => route_2
    )

[2] => Array
    (
        [safe_route] => no
        [route_name] => route_3
    )

)

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.