Jump to content

Remove elements from arrays


Jaswinder
Go to solution Solved by bsmither,

Recommended Posts

hi

I am having a multidimensional array in $a.

i get this result after using print_f

Array (
 [0] => Array ( [sno] => 4 [num1] => 45 [num2] => 45 [result] => 2025 )
 [1] => Array ( [sno] => 17 [num1] => 34 [num2] => 36 [result] => 1224 )
 [2] => Array ( [sno] => 2 [num1] => 78 [num2] => 5 [result] => 390 )
)

using foreach and converting into individual arrays

foreach($a as $key => $value)
	{
		print_r($key = $value); echo "<br/>";
         }

and the result is

Array ( [sno] => 4 [num1] => 45 [num2] => 45 [result] => 2025 )
Array ( [sno] => 17 [num1] => 34 [num2] => 36 [result] => 1224 )
Array ( [sno] => 2 [num1] => 78 [num2] => 5 [result] => 390 )

now i want to remove num1 and num2 elements from each array..

so that the resulting array contains 2 elements sno and result

i tried unset() but not getting result. any help

Link to comment
Share on other sites

  • Solution

You tried unset() specifically how?

Was:
foreach($a as $key => $value)
{
  print_r($key = $value); echo "<br/>";
}
 
Now try:
foreach($a as $key => $value)
{
  unset($a[$key]['num1'], $a[$key]['num2']);
  print_r($a[$key]); echo "<br/>";
}

According to the PHP manual for foreach(), $value is a copy from $a. In order to change $value that is actually part of $a, you would need:

foreach($a as $key => &$value)

Edited by bsmither
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.