Jump to content

Remove elements from arrays


Jaswinder

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
https://forums.phpfreaks.com/topic/288028-remove-elements-from-arrays/
Share on other sites

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)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.