Remove array element by checking a value php - php

I have an array as follows
[0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']]
I need to remove the elements with classId 2 or 4 from array and the expected result should be
[0=>['classId'=>3,'Name'=>'Doe']]
How will i achieve this without using a loop.Hope someone can help

You can use array_filter in conjunction with in_array.
$array = [0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']];
var_dump(
array_filter($array, function($item){return !in_array($item["classId"], [2,4]);})
);
Explanation
array_filter
Removes elements from the array if the call-back function returns false.
in_array
Searches an array for a value; returns boolean true/false if the value is (not)found.

Try this:
foreach array as $k => $v{
if ($v['classId'] == 2){
unset(array[$k]);
}
}
I just saw your edit, you could use array_filter like so:
function class_filter($arr){
return ($arr['classId'] == "whatever");
}
array_filter($arr, "class_filter");
Note: you'll still need to loop through a multi-dimensional array I believe.

Related

Safety net for array_slice

I read that array_merge will return NULL if you try to merge an empty array and any other array. That's not what I hope to do. I am trying to merge an array with a new array that is actually a slice of another array. ($i is an integer).
$forgotten = array_slice($matches, $i) ;
$leftOvers = array_merge($leftOvers, $forgotten);
The question is, what does array_slice return when the index is not found? If it can return null, should I do something like this:
$forgotten = array_slice($matches, $i) || array();
Also, is there any difference between using array_merge like this, and pushing $forgotten into leftOvers?
if you use array_merge over an empty array and another array it will return an array composed with the elements of the not empty array. If you try to merge two empty arrays it will return an empty array.
array_slice($matches, $i)
array_slice returns an array with all the elements of $matches with index greater or equal $i, if there are no such elements it will return an empty array.
Using array_push:
array_push($leftOvers, $forgotten)
$result will enqueue an array as a value the end of $leftOvers.
Always try to read the php man when you use a new php function, also you could get all these answers just trying to execute the functions in a test.php file.

Removing empty elements from php array

Im looking for a way to remove empty elements from an array.
Im aware of array_filter() which removes all empty values.
The thing is that i consider a string containing nothing but spaces, tabs and newlines also to be empty.
So what is best used in this case?
Use trim() in callback for array_filter:
$array = array_filter($array, function ($v) { return (bool)trim($v); });
Or shorter version (with implicit type-casting):
$array = array_filter($array, 'trim');
php empty()
bool empty ( mixed $var )
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
Something like should do:
foreach($array as $key => $stuff)
{
if(empty(stuff))
{
unset($array[$key]);
}
}
$array = array_values($array );// to reinstate the numerical indexes.
I know this may be late to answer but it is for those who may have interest in other ways to solve this. It is my own way of doing it.
function my_array_filter($my_array)
{
$final_array = array();
foreach ( $my_array as $my_arr )
{
//check if array element is not empty
if (!empty($my_arr)) $final_array[] = $my_arr;
}
//remove duplicate elements
return array_unique( $final_array );
}
Hope someone finds this useful.

Return true elements from a Multi-checkbox true/ false array in php

I am quite bad at php. I have a Multicheckbox that outputs an array this way:
Array
(
[value1] => true
[value2] => false
[value2] => false
[value4] => false
[value5] => true
[value6] => false
)
I would like to return an array with only the elements (values) that are true. Then I will apply this:
$list_of_true_values = explode(',', $array_i_am_looking_for);
return $list_of_true_values;
As in the end I want to return this: value1,value5.
Thanks'
As Rajat has said you can use the array_keys() function. I'd also add that if you're looking to get an output of value1,value5, you shouldn't use explode(), but rather, it's duel, implode().
return implode(",", array_keys($array, true));
Is all you need.
As per your comment, if you'd like to wrap the keys in single quotes:
$keys = array_keys($array, true);
array_walk($keys, function(&$v, $k){$v = "'" . $v . "'";});
return (implode(",", $keys));
This is called Anonymous (Lambda) Syntax.
array_keys($array, true); will return array with keys with true value, which you need..
If you specifically have true/false values, you can use PHP's array_filter() without a callback:
$values = array_filter($_POST['data']);
Without a callback function, array_filter() will filter out all of the "false" and empty values. Then, to get the keys from the list obtained, you can then use PHP's array_keys() as only the ones with "true" values will be in the $values array:
return array_keys($values);
In your exact specification, using the optional $search_value parameter of array_keys() may suffice, as Rajat has shown in his answer. However, I would suggest using array_filter() if you ever need to extend the list of values you want to keep or discard.

selecting an array key based on partial string

I have an array and in that array I have an array key that looks like, show_me_160 this array key may change a little, so sometimes the page may load and the array key maybe show_me_120, I want to now is possible to just string match the array key up until the last _ so that I can check what the value is after the last underscore?
one solution i can think of:
foreach($myarray as $key=>$value){
if("show_me_" == substr($key,0,8)){
$number = substr($key,strrpos($key,'_'));
// do whatever you need to with $number...
}
}
I ran into a similar problem recently. This is what I came up with:
$value = $my_array[current(preg_grep('/^show_me_/', array_keys($my_array)))];
you would have to iterate over your array to check each key separately, since you don't have the possibility to query the array directly (I'm assuming the array also holds totally unrelated keys, but you can skip the if part if that's not the case):
foreach($array as $k => $v)
{
if (strpos($k, 'show_me_') !== false)
{
$number = substr($k, strrpos($k, '_'));
}
}
However, this sounds like a very strange way of storing data, and if I were you, I'd check if there's not an other way (more efficient) of passing data around in your application ;)
to search for certain string in array keys you can use array_filter(); see docs
// the array you'll search in
$array = ["search_1"=>"value1","search_2"=>"value2","not_search"=>"value3"];
// filter the array and assign the returned array to variable
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($key){
return(strpos($key,'search_') !== false);
},
// flag to let the array_filter(); know that you deal with array keys
ARRAY_FILTER_USE_KEY
);
// print out the returned array
print_r($foo);
if you search in the array values you can use the flag 0 or leave the flag empty
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
},
// flag to let the array_filter(); know that you deal with array value
0
);
or
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
}
);
if you search in the array values and array keys you can use the flag ARRAY_FILTER_USE_BOTH
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value, $key){
return(strpos($key,'search_') !== false or strpos($value,'value') !== false);
},
ARRAY_FILTER_USE_BOTH
);
in case you'll search for both you have to pass 2 arguments to the callback function
You can also use a preg_match based solution:
foreach($array as $str) {
if(preg_match('/^show_me_(\d+)$/',$str,$m)) {
echo "Array element ",$str," matched and number = ",$m[1],"\n";
}
}
filter_array($array,function ($var){return(strpos($var,'searched_word')!==FALSE);},);
return array 'searched_key' => 'value assigned to the key'
foreach($myarray as $key=>$value)
if(count(explode('show_me_',$event_key)) > 1){
//if array key contains show_me_
}
More information (example):
if array key contain 'show_me_'
$example = explode('show_me_','show_me_120');
print_r($example)
Array ( [0] => [1] => 120 )
print_r(count($example))
2
print_r($example[1])
120

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