Remove element from array if string contains any of the characters - php

Remove element from array if string contains any of the characters.For example Below is the actual array.
array(1390) {
[0]=>
string(9) "Rs.52.68""
[1]=>
string(20) ""php code generator""
[2]=>
string(9) ""Rs.1.29""
[3]=>
string(21) ""php codes for login""
[4]=>
string(10) ""Rs.70.23""
}
I need the array to remove all the elements which start with RS.
Expected Result
array(1390) {
[0]=>
string(20) ""php code generator""
[1]=>
string(21) ""php codes for login""
}
What i tried so far :
foreach($arr as $ll)
{
if (strpos($ll,'RS.') !== false) {
echo 'unwanted element';
}
From above code how can i remove unwanted elements from array .

You can get the $key in the foreach loop and use unset() on your array:
foreach ($arr as $key => $ll) {
if (strpos($ll,'RS.') !== false) {
unset($arr[$key]);
}
}
Note that this would remove none of your items as "RS" never appears. Only "Rs".

This sounds like a job for array_filter. It allows you to specify a callback function that can do any test you like. If the callback returns true, the value if returned in the resulting array. If it returns false, then the value is filtered out.
$arr = array_filter($arr,
function($item) {
return strpos($item, 'Rs.') === false;
});

Rs is different than RS you want to use stripos rather than strpos for non case sensitive checking
foreach($arr as $key => $ll)
{
if (stripos($ll,'RS.') !== false) {
unset($arr[$key]);
}
}
or use arrayfilter as pointed out

Related

Remove empty entries in associated array php

I have tried all the solutions suggested in this post but have not been able to make them work in my case.
My array :
array(2) {
["number_s"]=>
array(14) {
[0]=>
string(2) "22"
[1]=>
string(2) "23"
[2]=>
string(0) ""
[3]=>
string(0) ""
[4]=>
string(0) ""
}
["player_name"]=>
array(14) {
[0]=>
string(9) "John Doe"
[1]=>
string(11) "Jack Sparrow"
[2]=>
string(0) ""
[3]=>
string(0) ""
[4]=>
string(0) ""
}
}
I would like to remove all the empty entries but how to do that ?
Thanks a lot for help
It seems like array_filter for each subarray will do what you want.
$array['number_s'] = array_filter($array['number_s']);
$array['player_name'] = array_filter($array['player_name']);
When called without callback function it just removes all empty entries. See docs for details.
But be aware that it will remove "0" and all values which considered empty.
Assuming there aren't arbitrary numbers of subarrays, you may transverse them (as references) and use unset to remove them from the array:
foreach ($array as &$subarray) {
foreach ($subarray as $key => $value) {
if (empty($value)) {
unset($subarray[$key]);
}
}
}
It's simpler with a functional approach:
$array = array_map(
fn($subarray) => array_filter($subarray),
$array
);
If the array may have arbitrary levels, you may implement a recursive function:
function remove_empty_recursive(array &$array)
{
foreach($array as $key => &$value) {
if (empty($value)) {
unset($array[$key]);
} elseif (is_array($value)) {
remove_empty_recursive($value);
}
}
}
Notice all those solutions assume you want to remove "0", 0 and false from the array. Otherwise, you need to specify another criteria, instead of using empty. For instance:
$array = array_map(
fn($subarray) => array_filter(
$subarray,
fn($value) => !empty($value) || is_numeric($value) || $value === false
),
$array
);

how to take array with specific char?

i have array
Example :
array(3) { [0]=> string(6) "{what}" [1]=> string(5) "[why]" [2]=> string(5) "(how)" }
and then how to take array with specific char ("{") ?
Is my understanding here correct? You want to get items in array that has a "{" Character. Then why not just loop over it and check the item if it has that character and push it in a new array.
$array_with_sp_char = array();
foreach ($arr_items as $item) {
if (strpos($item, '{') !== FALSE) {
array_push($array_with_sp_char, $item);
}
}
Just iterate through your array and filter out the values you are interested in, in your case i guess it's the values that contain the Char "{"
A possible implementation:
$result = array_filter($your_array, function($value) {
return preg_match('/{/', $value);
});
Use a combination of array_filter and strpos:
$array = [
"{what}",
"[why]",
"(how)"
];
$array = array_filter($array, function($value) {
return strpos($value, '{') !== false;
});
print_r($array);
That will give you:
Array
(
[0] => {what}
)

Recursive function for checking multidimensional arrays

Really struggling with this. I have a multidimensional array n levels deep. Each 'array level' has information I need to check (category) and also check if it contains any arrays.
I want to return the category ids of all the arrays which have a category and do not contain an array (i.e. the leaves). I can echo output properly, but I am at a loss as how to return the ids in an array (without referencing)
I have tried RecursiveIteratorIterator::LEAVES_ONLY and RecursiveArrayIterator but I don't think they work in my case? (Maybe I am overlooking something)
$array
array(2) {
["1"]=>
string(5) "stuff"
["2"]=>
array(2) {
["category"]=>
string(1) "0"
["1"]=>
array(3) {
[0]=>
array(3) {
["category"]=>
string(1) "1"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["category"]=>
string(1) "2"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["1"]=>
string(5) "stuff"
["32"]=>
string(5) "stuff"
}
}
}
}
My function
public function recurs($array, $cats = [])
{
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$this->recurs($value, $cats);
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return $array_cat;
}
}
Calling it
$cats_array = $this->recurse($array)
Output echoed
echoing the category here works fine: 1
echoing the category here works fine: 2
How do I return the ids in an array to use in the $cats_array variable?
EDIT: The output should match the echo, so I should get an array containing (1, 2) since they are the only arrays with categories and no arrays within them
array(2){
[0]=>
int(1) "1"
[1]=>
int(1) "2"
}
If I understood you correctly this function will do the job:
function getCategories(array $data)
{
if ($subArrays = array_filter($data, 'is_array')) {
return array_reduce(array_map('getCategories', $subArrays), 'array_merge', array());
};
return array_key_exists('category', $data) ? array($data['category']) : array();
}
If the array contains any sub-arrays they will be returned by array_filter and you will enter the if statement. array_map will apply the function recursively to the sub-arrays and array_reduce will merge the results.
If the array doesn't contain any sub-arrays you will not enter the if statement and the function will return an array with the category if it is present.
Note that you might need to use array_unique to return unique categories.
Also for small performance optimization instead of array_key_exists you can use isset($array[$key]) || array_key_exists($key, $array).
Update
If you want to update your function to make it work you have to recursively collect and merge the sub results. In the following example I introduced a new variable for this:
public function recurs($array, $cats = [])
{
$result = [];
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$result = array_merge($result, $this->recurs($value, $cats));
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return [$array_cat];
}
return $result;
}

Remove from multidimensional array if value partially matches

I write a multilingual wordpress homepage. I need to load all languages into array, then detect the user language and then depending on user language remove the other languages from the array.
I want to do partial check on array to see if "Title" contains _DE or _ES and then depending on result remove one or the other from array.
So far I have
Data
array(2) {
[1]=> array(3) { ["order"]=> string(1) "1" ["title"]=> string(9) "Slider_ES" ["id"]=> string(3) "500" }
[2]=> array(3) { ["order"]=> string(1) "2" ["title"]=> string(11) "Slider_DE" ["id"]=> string(3) "493" }
}
Logic
$current_language = get_locale(); // Wordpress function which returns either es_ES or de_DE codes
if ($current_language == es-ES) {
foreach ($array as $key => $item) {
if ($item['title'] === '_DE') {
unset($array[$key]);
}
}
} else {
foreach ($array as $key => $item) {
if ($item['title'] === '_ES') {
unset($array[$key]);
}
}
}
What did I miss?
You can use the strpos function which is used to find the occurrence of one string inside other like this:
if (strpos($item['title'],'_DE') !== false) {
unset($array[$key]);
}

Result saves in two arrays

I'm playing around with foreach and Simple HTML dom there I'm trying to save down some links to a array. But my problem is that the result saves in two arrays instead of one array.
foreach($html->find('div[class^=voucher success]') as $q)
{
#$var = $q->find('a', 0)->href;
$pos = strpos($var, "/ut/");
if($pos === false)
{
$item[] = $var;
}
var_dump($item);
}
Dump:
array(1) {
[0]=> string(10) "/hm?v=2726" }
array(2) {
[0]=> string(10) "/hm?v=2726" [1]=> string(10) "/hm?v=2732"
}
Why is that? What have I done wrong?
It's not saving in two arrays. You're dumping the data at the end of every foreach loop. Therefore it dumps twice, because there is two loops in the foreach.
To see the final result of $item you need to dump after the foreach.
foreach($html->find('div[class^=voucher success]') as $q)
{
#$var = $q->find('a', 0)->href;
$pos = strpos($var, "/ut/");
if($pos === false)
{
$item[] = $var;
}
}
var_dump($item);
The output would now be:
array(2) {
[0]=> string(10) "/hm?v=2726" [1]=> string(10) "/hm?v=2732"
}
Why do you think it is in two arrays? Your var_dump is inside your loop, so it is just dumping each time you iterate.

Categories