$alllist = array(
"link" => $link,
"title" => $title,
"imgurl" => $imgURL,
"price" => $price,
"mname" => $merchantname,
"description" => $description,
);
$all[] = $alllist;
I am trying to filter the array $all where mname is a certain value, let's say 'Amazon'. How do I do that?
I tried this, but it did not work:
reset($all);
$all_filter = array_filter($all, function(filter) use ($all) {
$key = key($all);
next($all);
return key($all) === 'Amazon';
});
I think this what you want:
$name = 'Amazon';
$all_filter = array_filter($all, function (array $item) use ($name) {
return array_key_exists('mname', $item) && $item['mname'] === $name;
});
$all[] = array("link"=> 1, "title"=> 2, "imgurl"=> 3,
"price"=>4, "mname"=>'Amazon', "description"=>5);
$all[] = array("link"=> 1, "title"=> 2, "imgurl"=> 3,
"price"=>4, "mname"=>'Facebook', "description"=>5);
$filtered = array_filter($all, function($item) {
return $item['mname'] === 'Amazon';
});
var_dump($filtered);
array_filter() will iterate over the array for you. You don't need to call reset() or next().
You should look at the array_filter() documentation for more info and examples.
$all_filter = array_filter($all, function($item) {
return $item['mname'] === 'Amazon';
});
It looks like you're making it more complex than it needs to be. The callback should just return a boolean value. If you don't want to hard-code the value you want to filter by (e.g. 'Amazon'), you can pass it into the callback with use.
$filter_value = 'Amazon';
$all_filter = array_filter($all, function($item) use($filter_value) {
// without use($filter_value), $filter_value will be undefined in this scope
return $item['mname'] == $filter_value;
});
Returning the boolean expression $item['mname'] == $filter_value; will determine which items have mname values that match the filter value, and those items will be included in the result.
Related
I have seen so many answers but i just can't get it to work.
I want to check if there is a (partial) value in the array.
//Get DNS records
$result = dns_get_record("php.net", DNS_ALL);
print_r($result);
//If the value php-smtp3.php.net is found, echo it
if (in_array("php-smtp3.php.net", $result )) {
echo "Found!";
}
added : json_encoded $result, from my network
[
{
"host" : "php.net" ,
"class" : "IN" ,
"ttl" : 375 ,
"type" : "A" ,
"ip" : "208.43.231.9"
} ,
{
"host" : "php.net" ,
"class" : "IN" ,
"ttl" : 375 ,
"type" : "NS" ,
"target" : "dns2.easydns.net"
}
]
Thank you all so much, i think i am almost there and sorry if i dont understand fully. This is what i have now:
$result = dns_get_record("php.net", DNS_ALL);
print_r($result);
$result = json_decode($result, true);
$result = array_filter($result, function($x) {
return in_array("smtp", $x, true);
//If in the array, no matter where, is "smtp" then echo "found" is what i am trying to achieve
echo "<h1>FOUND</h1>";
});
Update:
$result = dns_get_record("php.net", DNS_ALL);
$result = json_decode($data, true);
function process($data) {
foreach ($data as $key => $value) {
if (is_array($value)) {
return process($value);
}
if (is_string($value) && strpos($value,'smtp') !== false) {
echo "FOUND";
return true;
}
}
return false;
}
$result = array_filter($result, 'process');
I am trying both ways... so sorry you guys, i am stuck trying to get a response from the DNS entry for a simple string. The actual idea behind this is:
1) Check a DNS record for a domain
2) Check if there is a SPF record ANYWHERE
3) If so, just say "found SPF record"
$values = array_reduce(
dns_get_record("php.net", DNS_ALL),
function ($out, $item) {
return array_merge($out, array_values($item));
},
[]
);
var_dump(in_array("dns2.easydns.net", $values));
//Result is bool(true)
After using json_decode, your data returns a multi dimensional array where some arrays also contain an array.
What you might do if you want to check for a partial value so if the string contains a substring is to use strpos but you have to loop throug all the strings, also in the sub arrays.
Therefore you might use array_filter in combination with a recursive approach.
So for example if you want to look for the substring smtp3 you could use:
function process($data) {
foreach ($data as $key => $value) {
if (is_array($value)) {
return process($value);
}
if (is_string($value) && strpos($value,'smtp3') !== false) {
return true;
}
}
return false;
}
$result = array_filter($result, 'process');
print_r($result);
See the php demo
All you need to do is to flatten the result and search for a value, like this:
<?php
$values = array_reduce(
dns_get_record("php.net", DNS_ALL),
function ($out, $item) {
return array_merge($out, array_values($item));
},
[]
);
var_dump(in_array("dns2.easydns.net", $values));
I`m using $_POST array with results of checkbox's selected from a form.
I'm thinking of using php in_array function but how could I extract only values that start with chk Given the following array:
Array (
[chk0] => 23934567622639616
[chk3] => 23934567622639618
[chk4] => 23934567622639619
[select-all] => on
[process] => Process
)
Thanks!
Simple and fast
$result=array();
foreach($_POST as $key => $value){
if(substr($key, 0, 2) == 'chk'){
$result[$key] = $value;
}
}
Lots of ways to do this, I like array_filter.
Example:
$result = array_filter(
$_POST,
function ($key) {
return strpos($key, "chk") === 0;
},
ARRAY_FILTER_USE_KEY
);
Here's a solution from http://php.net/manual/en/function.preg-grep.php
<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
?>
I would use array_filter
$ary = array_filter($originalArray,
function($key){ return preg_match('/chk/', $key); },
ARRAY_FILTER_USE_KEY
);
I am validating a form in which some fields must be in particular format, and some just have to be filled... So I use something like
$trusty = filter_input_array(INPUT_POST , array(
'status'=>array(
'filter'=>FILTER_VALIDATE_INT,
'options'=>array('min_range' => 1, 'max_range' => 3, 'default'=>2)
),
'tags'=>array(
'filter'=>FILTER_CALLBACK,
'options'=>function($value) {
if (mb_strpos($value, ",") === false) {
return trim($value);
} else {
$tags = explode(",", $value);
$tags = array_map(function($val) {
return trim($val);
}, $tags);
return $tags;
}
},
)
));
to validate thoose which need particular format, but I also have fields 'title' and 'body' which can be anything but should not be empty. Of course I can check it separatly but I'd like to do all validation in one place. And my question is:
Is there a filter, or flag that checks if variable is empty?
Maybe something like this:
$trusty = filter_input_array(INPUT_POST , array(
'status'=>array(
'filter'=>FILTER_VALIDATE_INT,
'options'=>array('min_range' => 1, 'max_range' => 3, 'default'=>2)
),
'tags'=>array(
'filter'=>FILTER_CALLBACK,
'options'=>function($value) {
if (mb_strpos($value, ",") === false) {
return trim($value);
} else {
$tags = explode(",", $value);
$tags = array_map(function($val) {
return trim($val);
}, $tags);
return $tags;
}
},
) ,
'title'=>array(
'filter'=>FILTER_CALLBACK,
'options'=>function($value) {
return empty($value);
}
)
));
This should also work:
'title'=>array(
'filter'=>FILTER_CALLBACK,
'options'=>'empty'
)
There is a function in php to check empty variable
empty ( mixed $var )
You Can Have a Look: this
In PHP Consider this function:
function test($name, $age) {}
I need to somehow extract the parameter names (for generating custom documentations automatically) so that I could do something like:
get_func_argNames('test');
and it would return:
Array['name','age']
Is this even possible in PHP?
You can use Reflection :
function get_func_argNames($funcName) {
$f = new ReflectionFunction($funcName);
$result = array();
foreach ($f->getParameters() as $param) {
$result[] = $param->name;
}
return $result;
}
print_r(get_func_argNames('get_func_argNames'));
//output
Array
(
[0] => funcName
)
It's 2019 and no one said this?
Just use get_defined_vars():
class Foo {
public function bar($a, $b) {
var_dump(get_defined_vars());
}
}
(new Foo)->bar('first', 'second');
Result:
array(2) {
["a"]=>
string(5) "first"
["b"]=>
string(6) "second"
}
This is an old question I happened on looking for something other then Reflection, but I will toss out my current implementation so that it might help someone else. Using array_map
For a method
$ReflectionMethod = new \ReflectionMethod($class, $method);
$params = $ReflectionMethod->getParameters();
$paramNames = array_map(function( $item ){
return $item->getName();
}, $params);
For a function
$ReflectionFunction = new \ReflectionFunction('preg_replace');
$params = $ReflectionFunction->getParameters();
$paramNames = array_map(function( $item ){
return $item->getName();
}, $params);
echo '<pre>';
var_export( $paramNames );
Outputs
array(
'0' => 'regex',
'1' => 'replace',
'2' => 'subject',
'3' => 'limit',
'4' => 'count'
)
Cheers,
In addition to Tom Haigh's answer if you need to get the default value of optional attributes:
function function_get_names($funcName){
$attribute_names = [];
if(function_exists($funcName)){
$fx = new ReflectionFunction($funcName);
foreach ($fx->getParameters() as $param){
$attribute_names[$param->name] = NULL;
if ($param->isOptional()){
$attribute_names[$param->name] = $param->getDefaultValue();
}
}
}
return $attribute_names;
}
Useful for variable type validation.
#Tom Haigh, or do it more classy:
function getArguments( $funcName ) {
return array_map( function( $parameter ) { return $parameter->name; },
(new ReflectionFunction($funcName))->getParameters() );
}
// var_dump( getArguments('getArguments') );
func_get_args
function my($aaa, $bbb){
var_dump( func_get_args() );
}
my("something","something"); //result: array('aaa' => 'something', 'bbb' => 'something');
also, there exists another global functions: get_defined_vars(), that returns not only function, but all variables.
Example:
$arr = array(1 => 'Foo', 5 => 'Bar', 6 => 'Foobar');
/*... do some function so $arr now equals:
array(0 => 'Foo', 1 => 'Bar', 2 => 'Foobar');
*/
Use array_values($arr). That will return a regular array of all the values (indexed numerically).
PHP docs for array_values
array_values($arr);
To add to the other answers, array_values() will not preserve string keys. If your array has a mix of string keys and numeric keys (which is probably an indication of bad design, but may happen nonetheless), you can use a function like:
function reset_numeric_keys($array = array(), $recurse = false) {
$returnArray = array();
foreach($array as $key => $value) {
if($recurse && is_array($value)) {
$value = reset_numeric_keys($value, true);
}
if(gettype($key) == 'integer') {
$returnArray[] = $value;
} else {
$returnArray[$key] = $value;
}
}
return $returnArray;
}
Not that I know of, you might have already checked functions here
but I can imagine writing a simple function myself
resetarray($oldarray)
{
for(int $i=0;$i<$oldarray.count;$i++)
$newarray.push(i,$oldarray[i])
return $newarray;
}
I am little edgy on syntax but I guess u got the idea.