I am having below array. I would like to get the value which is having '1' and the key should be 'wf_status_step%'. How to write a PHP script for this?
[ini_desc] => 31.07 Initiative1
[mea_id] => 1
[status] => 4
[name] => 31.07 Measure1
[scope] => NPR
[sector] =>
[mea_commodity] => 8463
[commodity_cls] => IT
[delegate_usrid] => 877
[wf_status_step1] => 2
[wf_status_step2] => 1
[wf_status_step3] => 0
[wf_status_step4] => 0
[wf_status_step5] => 0
A shorter version that will find all keys with value 1 that start with 'wf_status_step'
$keys = array_filter(array_keys($array,1),function($key){
return stripos($key,'wf_status_step') === 0;
});
Long answer
foreach($your_array as $key=>$value)
{
if(strpos($key, 'f_status_step') !== FALSE) // will check for existence of "f_status_step" in the keys
{
if($value == 1) // if the value of that key is 1
{
// this is your target item in the array
}
}
}
You can iterate over the keys in the array to find all the keys that match your pattern, and simulatenously check associated values. Something like this:
<?php
$found_key = null;
foreach(array_keys($my_array) as $key) {
if(strpos($key, "wf_status_step") === 0) {
//Key matches, test value.
if($my_array[$key] == 1) {
$found_key = $key;
break;
}
}
}
if( !is_null($found_key) ) {
//$found_key is the one you're looking for
} else {
//Not found.
}
?>
If you want to be more sophisticated about matching the key, you can use regular expressions.
You can also use the foreach($my_array as $key=>$value)
mechanism that is shown in some other answers, instead of using array_keys
.
foreach ($array_name as $key => $value) {
if (strpos($key, 'wf_status_step') === 0) {
if ($value == 1) {
// do something
}
}
}
try this
$wf_status_array = array();
foreach ($array as $key => $value) {
if($value === 1 && preg_match_all('~^wf_status_step[0-9]+$~',$key,$res)){
$key = $res[0][0];
$wf_status_array[$key] = $array[$key];
}
}
print_r($wf_status_array)