array_map and htmlentities - php

I've been trying using array_map to convert characters to HTML entities with htmlentities() like this:
$lang = array_map('htmlentities', $lang);
My array looks like this:
$lang = array();
$lang['var_char1']['varchar2'] = 'Some Text';
But I keep getting this errors:
Warning: htmlentities() expects parameter 1 to be string, array given
in /home/user/public_html/foo/lang/en.inc.php on line 1335
Does anyone know what could be the problem? Thank you!

Use array_walk_recursive. array_map doesn't work with multidimensional arrays:
array_walk_recursive($lang, function (&$value) {
$value = htmlentities($value);
});

Because $lang is a two dimensional array, so it won't work
For two dimensional array you need to use for loop
foreach($$lang as &$l):
$l = array_map('htmlentities', $l);
}

$lang['var_char1']['varchar2'] defines a multidimensional array, so each element of $lang is also an array. array_map() iterates through $lang, passing an array to htmlentities() instead of a string.

array_map() doesn't work recursively. If you know your array is always two levels deep you could loop through it and use array_map on the sub-arrays.

if you like quotes
function stripslashes_array(&$arr) {
array_walk_recursive($arr, function (&$val) {
$val = htmlentities($val, ENT_QUOTES);
});
}
multiple array in post, get, dll
stripslashes_array($_POST);
stripslashes_array($_GET);
stripslashes_array($_REQUEST);
stripslashes_array($_COOKIE);

Each element in $lang is an array, so the function you pass to array_map should take an array as an argument. That is not the case for 'htmlentities' which takes a string.
You can:
$map_htmlentities = function(array) { return array_map('htmlentities', array); };
and then
$lang = array_map($map_htmlentities, $lang);
From PHP 7.4 on you can use lambdas:
$lang = array_map(fn($arr) => array_map('htmlentities', $arr), $lang);

Related

How to put PHP variable in array

$booked_seat=array(1,2);
if(in_array($seat,$booked_seat)){
$booked="red"; $book_seat="data-book='1'";
} else {
$booked=""; $book_seat="";
}
I want to put PHP variable in array
$booked_seat=array($id);
Is this possible in any way define variable in array?
You can do like this using explode() & array_shift() in php :
$str = '1,2,3';
$arr = [explode(",", $str)];
echo "<pre>";
print_r(array_shift($arr));
If you want a string instead of an array of numbers, you can use the join method http://php.net/manual/en/function.join.php.
$str = join(',', array(1, 2, 3));
If you are wanting to create an array out of a string like '1,2,3' you could use the explode method http://php.net/manual/en/function.explode.php.
$arr = explode(",", "1,2,3");

Array inside an array(2 dimensional array) convert to string

How does one correctly/properly convert an array like this?
For example, if I do, print_r($array);
It would print out a result like,
Array([0] => Array([0] => 5))
How did that array come to be?
I know how to convert a single array to string by using implode(). It however, doesn't work on an array inside an array.
I don't think using implode() twice will do the trick. Does anyone have any idea?
if you want to get the array as string, use print_r with the second parameter true
$string = print_r($array, true);
or serialize
$string = serialize($array);
or json_encode
$string = json_encode($array);
And if you want to use implode, use this with array_walk_recursive
function test_print($item, $key)
{
if (is_array($item))
{
echo implode(',', $item);
}
}
array_walk_recursive($array, 'test_print');
Why not just loop it using a foreach construct ?
Something like this..
<?php
$arr = array(0=>array(0=>5),1=>array(0=>6));
foreach($arr as $arr1)
{
$str.=implode(' ',$arr1).",";
}
echo rtrim($str,','); //"prints" 5,6

PHP list() assign - trim before assign or any other function?

I am using a list() assign in PHP so I could assign array values to more variables at once.
Thing is I need to trim() the array inputs before - of course you could do a foreach on array before or after that - but is there a way to cast trim as a some kind of assignment filter - or at least trim the array inline (no external function or foreach)?
The question is more like general - can you add some filter function to a list() assigment?
EDIT:
For those who are looking for the "simplier" solution with foreach:
foreach($items as $k => $v) $item[$k] = trim($v);
list($var1,$var2,$var3,$var4) = $items;
Cannot give you an easier way than array_map():
list($var1,$var2,$var3,$var4) = array_map('trim', $items);
The "trick" here is that array_map will apply the function to every element of the array, and then return the modified array - which will then be used by list.
Little Demo
$items = array_map('trim', $items);
list($var1,$var2,$var3,$var4) = $items;
As far as I know list does not accept a kind of filter. array_map could be a more direct way:
list($var1,$var2,$var3,$var4) = array_map('trim', $items)

php turn this array into integer series

this is the output of my array
[["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]]
but I would like this to look like
[1,1,1,1,1,1,1]
how would this be achieved in php, it seems everything I do gets put into an object in the array, when I don't want that. I tried using array_values and it succeeded in returning the values only, since I did have keys originally, but this is still not the completely desired outcome
$yourArray = [["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"],["1"]];
use following code in PHP 5.3+
$newArray = array_map(function($v) {
return (int)$v[0];
}, $yourArray);
OR use following code in other PHP version
function covertArray($v) {
return (int)$v[0];
}
$newArray = array_map('covertArray', $yourArray)
You could always do a simple loop...
$newArray = array();
// Assuming $myArray contains your multidimensional array
foreach($myArray as $value)
{
$newArray[] = $value[0];
}
You could beef it up a little and avoid bad indexes by doing:
if( isset($value[0]) ) {
$newArray[] = $value[0];
}
Or just use one of the many array functions to get the value such as array_pop(), array_slice(), end(), etc.

Type check in all array elements

Is there any simple way of checking if all elements of an array are instances of a specific type without looping all elements? Or at least an easy way to get all elements of type X from an array.
$s = array("abd","10","10.1");
$s = array_map( gettype , $s);
$t = array_unique($s) ;
if ( count($t) == 1 && $t[0]=="string" ){
print "ok\n";
}
You cannot achieve this without checking all the array elements, but you can use built-in array functions to help you.
You can use array_filter to return an array. You need to supply your own callback function as the second argument to check for a specific type. This will check if the numbers of the array are even.
function even($var){
return(!($var & 1));
}
// assuming $yourArr is an array containing integers.
$newArray = array_filter($yourArr, "even");
// will return an array with only even integers.
As per VolkerK's comment, as of PHP 5.3+ you can also pass in an anonymous function as your second argument. This is the equivalent as to the example above.
$newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );
Is there any simple way of checking if all elements of an array [something something something] without looping all elements?
No. You can't check all the elements of an array without checking all the elements of the array.
Though you can use array_walk to save yourself writing the boilerplate yourself.
You can also combine array_walk with create_function and use an anonymous function to filter the array. Something alon the lines of:
$filtered_array = array_filter($array, create_function('$e', 'return is_int($e)'))

Categories