remove subarrays in an array php

✔ Recommended Answer

You can do it like this :

foreach ($arr as $key => $value) {      if(is_array($value)){    $newarray[] = $key;   }else{     $newarray[] = $value;   }  } echo "<pre>";print_r($newarray);echo "</pre>";

Source: stackoverflow.com

Answered By: Anant V

Method #2

To remove subarrays in an array in PHP, you can use a combination of array functions such as array_filter() and array_values().

Here's an example code snippet that removes subarrays based on a specific condition:

php
<?php // Sample array with subarrays $myArray = array( array('id' => 1, 'name' => 'John'), array('id' => 2, 'name' => 'Jane'), array('id' => 3, 'name' => 'Mark'), array('id' => 4, 'name' => 'Lisa'), array('id' => 5, 'name' => 'Bob'), array('id' => 6, 'name' => 'Emma'), ); // Remove subarrays with id less than 4 $myArray = array_values(array_filter($myArray, function($subarray) { return $subarray['id'] >= 4; })); // Print the resulting array print_r($myArray); ?>

In the above example, we first define an array with subarrays $myArray. We then use the array_filter() function to filter out the subarrays that do not meet the condition, which in this case is that the id is less than 4. Finally, we use the array_values() function to re-index the array and get rid of any empty slots.

The resulting array will only contain subarrays with an id greater than or equal to 4.

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755