- benjamw / array_filter_recursive.php
- Footer
- benjamw / array_filter_recursive.php
- Footer
- Php – How to run array_filter recursively in a PHP array
- Best Solution
- Related Solutions
- Correctly setting up the connection
- Explanation
- Can prepared statements be used for dynamic queries?
- Deleting a single array element
- unset()
- \array_splice() method
- Deleting multiple array elements
- \array_diff() method
- \array_diff_key() method
benjamw / array_filter_recursive.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* Exactly the same as array_filter except this function |
* filters within multidimensional arrays |
* |
* @param array $array |
* @param callable|null $callback optional filter callback function |
* @param bool $remove_empty_arrays optional flag removal of empty arrays after filtering |
* |
* @return array filtered array |
*/ |
function array_filter_recursive ( array $ array , callable $ callback = null , bool $ remove_empty_arrays = false ): array |
foreach ( $ array as $ key => & $ value ) < // mind the reference |
if (is_array( $ value )) |
$ value = call_user_func_array(__FUNCTION__, array ( $ value , $ callback , $ remove_empty_arrays )); |
if ( $ remove_empty_arrays && ! ( bool ) $ value ) |
unset( $ array [ $ key ]); |
> |
> |
else |
if ( ! is_null( $ callback ) && ! $ callback ( $ value )) |
unset( $ array [ $ key ]); |
> |
elseif ( ! ( bool ) $ value ) |
unset( $ array [ $ key ]); |
> |
> |
> |
unset( $ value ); // kill the reference |
return $ array ; |
> |
Fix $remove_empty_arrays in recursion and added $key to callback argument list:
/** function array_filter_recursive * * Exactly the same as array_filter except this function * filters within multi-dimensional arrays * * @param array * @param string optional callback function name * @param bool optional flag removal of empty arrays after filtering * @return array merged array */ function array_filter_recursive($array, $callback = null, $remove_empty_arrays = false) < foreach ($array as $key =>& $value) < // mind the reference if (is_array($value)) < $value = array_filter_recursive($value, $callback, $remove_empty_arrays); if ($remove_empty_arrays && !(bool) $value) < unset($array[$key]); >> else < if (!is_null($callback) && !$callback($value, $key)) < unset($array[$key]); >elseif (!(bool) $value) < unset($array[$key]); >> > unset($value); // kill the reference return $array; >
or you can use call_user_func_array to «free» the function’s name
/** function array_filter_recursive * * Exactly the same as array_filter except this function * filters within multi-dimensional arrays * * @param array * @param string optional callback function name * @param bool optional flag removal of empty arrays after filtering * @return array merged array */ function array_filter_recursive($array, $callback = null, $remove_empty_arrays = false) < foreach ($array as $key =>& $value) < if (is_array($value)) < $value = call_user_func_array(__FUNCTION__, array($value, $callback, $remove_empty_arrays)); if ($remove_empty_arrays && ! (bool) $value) < unset($array[$key]); >> else < if ( ! is_null($callback) && ! $callback($value)) < unset($array[$key]); >elseif ( ! (bool) $value) < unset($array[$key]); >> > unset($value); return $array; >
Footer
You can’t perform that action at this time.
benjamw / array_filter_recursive.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** |
* Exactly the same as array_filter except this function |
* filters within multidimensional arrays |
* |
* @param array $array |
* @param callable|null $callback optional filter callback function |
* @param bool $remove_empty_arrays optional flag removal of empty arrays after filtering |
* |
* @return array filtered array |
*/ |
function array_filter_recursive ( array $ array , callable $ callback = null , bool $ remove_empty_arrays = false ): array |
foreach ( $ array as $ key => & $ value ) < // mind the reference |
if (is_array( $ value )) |
$ value = call_user_func_array(__FUNCTION__, array ( $ value , $ callback , $ remove_empty_arrays )); |
if ( $ remove_empty_arrays && ! ( bool ) $ value ) |
unset( $ array [ $ key ]); |
> |
> |
else |
if ( ! is_null( $ callback ) && ! $ callback ( $ value )) |
unset( $ array [ $ key ]); |
> |
elseif ( ! ( bool ) $ value ) |
unset( $ array [ $ key ]); |
> |
> |
> |
unset( $ value ); // kill the reference |
return $ array ; |
> |
Fix $remove_empty_arrays in recursion and added $key to callback argument list:
/** function array_filter_recursive * * Exactly the same as array_filter except this function * filters within multi-dimensional arrays * * @param array * @param string optional callback function name * @param bool optional flag removal of empty arrays after filtering * @return array merged array */ function array_filter_recursive($array, $callback = null, $remove_empty_arrays = false) < foreach ($array as $key =>& $value) < // mind the reference if (is_array($value)) < $value = array_filter_recursive($value, $callback, $remove_empty_arrays); if ($remove_empty_arrays && !(bool) $value) < unset($array[$key]); >> else < if (!is_null($callback) && !$callback($value, $key)) < unset($array[$key]); >elseif (!(bool) $value) < unset($array[$key]); >> > unset($value); // kill the reference return $array; >
or you can use call_user_func_array to «free» the function’s name
/** function array_filter_recursive * * Exactly the same as array_filter except this function * filters within multi-dimensional arrays * * @param array * @param string optional callback function name * @param bool optional flag removal of empty arrays after filtering * @return array merged array */ function array_filter_recursive($array, $callback = null, $remove_empty_arrays = false) < foreach ($array as $key =>& $value) < if (is_array($value)) < $value = call_user_func_array(__FUNCTION__, array($value, $callback, $remove_empty_arrays)); if ($remove_empty_arrays && ! (bool) $value) < unset($array[$key]); >> else < if ( ! is_null($callback) && ! $callback($value)) < unset($array[$key]); >elseif ( ! (bool) $value) < unset($array[$key]); >> > unset($value); return $array; >
Footer
You can’t perform that action at this time.
Php – How to run array_filter recursively in a PHP array
When I run count(array_filter($mm)) I get 3 as result since it is not recursive.
count(array_filter($mm), COUNT_RECURSIVE) also will not do because I actually need to run the array_filter recursively, and then count its result.
So my question is: how do I recursively run array_filter($mm) in this case?
My expected result here would be 4 .
Please note that I am not using any callback so I can exclude false, null and empty.
Best Solution
//This function filters an array and remove all null values recursively. > return array_filter($input); > ?> //Or with callback parameter (not tested) : > return array_filter($input, $callback); > ?>
Related Solutions
Php – How to prevent SQL injection in PHP
The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
- Using PDO (for any supported database driver):
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute([ 'name' => $name ]); foreach ($stmt as $row) < // Do something with $row >
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) < // Do something with $row >
If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.
Correctly setting up the connection
Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In the above example the error mode isn’t strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are throw n as PDOException s.
What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.
Explanation
The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute , the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.
Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains ‘Sarah’; DELETE FROM employees the result would simply be a search for the string «‘Sarah’; DELETE FROM employees» , and you will not end up with an empty table.
Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)'); $preparedStatement->execute([ 'column' => $unsafeValue ]);
Can prepared statements be used for dynamic queries?
While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.
For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.
// Value whitelist // $dir can only be 'DESC', otherwise it will be 'ASC' if (empty($dir) || $dir !== 'DESC')
Php – Deleting an element from an array in PHP
There are different ways to delete an array element, where some are more useful for some specific tasks than others.
Deleting a single array element
If you want to delete just one array element you can use unset() or alternatively \array_splice() .
If you know the value and don’t know the key to delete the element you can use \array_search() to get the key. This only works if the element does not occur more than once, since \array_search returns the first hit only.
unset()
Note that when you use unset() the array keys won’t change. If you want to reindex the keys you can use \array_values() after unset() , which will convert all keys to numerically enumerated keys starting from 0.
$array = [0 => "a", 1 => "b", 2 => "c"]; unset($array[1]); // ↑ Key which you want to delete
\array_splice() method
If you use \array_splice() the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values() , which will convert all keys to numerical keys.
\array_splice() needs the offset, not the key, as the second parameter.
$array = [0 => "a", 1 => "b", 2 => "c"]; \array_splice($array, 1, 1); // ↑ Offset which you want to delete
array_splice() , same as unset() , take the array by reference. You don’t assign the return values of those functions back to the array.
Deleting multiple array elements
If you want to delete multiple array elements and don’t want to call unset() or \array_splice() multiple times you can use the functions \array_diff() or \array_diff_key() depending on whether you know the values or the keys of the elements which you want to delete.
\array_diff() method
If you know the values of the array elements which you want to delete, then you can use \array_diff() . As before with unset() it won’t change the keys of the array.
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"]; $array = \array_diff($array, ["a", "c"]); // └────────┘ // Array values which you want to delete
\array_diff_key() method
If you know the keys of the elements which you want to delete, then you want to use \array_diff_key() . You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.
$array = [0 => "a", 1 => "b", 2 => "c"]; $array = \array_diff_key($array, [0 => "xy", "2" => "xy"]); // ↑ ↑ // Array keys which you want to delete
If you want to use unset() or \array_splice() to delete multiple elements with the same value you can use \array_keys() to get all the keys for a specific value and then delete all elements.