Click here to Skip to main content
15,900,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am having array values and i want to delete the first_name from the all sub-array.
following is my array and some code which i perform but not get expected result.

What I have tried:

<pre>$a = array(
      array(
        'id' => 5698,
        'first_name' => 'Peter',
        'last_name' => 'Griffin',
      ),
      array(
        'id' => 4767,
        'first_name' => 'Ben',
        'last_name' => 'Smith',
      ),
      array(
        'id' => 3809,
        'first_name' => 'Joe',
        'last_name' => 'Doe',
      )
    );


function removeElementWithValue($array, $key){
    foreach($array as $subKey => $subArray)
    {
       // print_r($array);
        if($subArray[$key])
        {
            echo "hi";
            unset($array[$subKey]);
        }
    }
    print_r($array);
}
$data= removeElementWithValue($a, "first_name");
Posted
Updated 2-Apr-18 2:34am
v3

1 solution

In your code you want to remove all arrays in the array $a that have an element with the key "first_name". You are not checking on the actual value. Try this:
PHP
function removeElementWithKey($array, $keyToRemove){
    foreach($array as $subArray)
    {
		foreach(array_keys($subArray) as $keyIndex => $key)
		{
			if ($key == $keyToRemove) 
            {
                array_splice($subArray, $keyIndex, 1);
            }
		}
    }
	return $array;
}
$data= removeElementWithKey($a, 'first_name');
print_r($data);
I used array_splice instead of unset(). This will leave your indexing in tact.
You can check the code here : PHP code- 39 lines - codepad[^]
 
Share this answer
 
v3
Comments
Dipali Nigade 2-Apr-18 8:28am    
no i want to remove first_name from array
Christiaan van Bergen 2-Apr-18 8:32am    
What? Then why do you state your question as : "i want to delete the id from the all sub-array." ? This makes no sense.
Please improve your question!
Dipali Nigade 2-Apr-18 8:33am    
yes sir i just improve that
Christiaan van Bergen 2-Apr-18 8:35am    
So I see that you changed the function call as well. So you want to remove all key-value elements with the key "first_name"? Regardless of the actual value?
Dipali Nigade 2-Apr-18 8:41am    
yes i want to remove all key-values elements with first_name

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900