I have this variable $variable = "own=1,contract_start=1";
and I wanna find this variable an array.
Array name is $variables this is my array:
Array
(
[own] => Array
(
[type] => bool
[value] => 0
)
[contr_name] => Array
(
[type] => bool
[value] => 0
)
[all_votes] => Array
(
[type] => int
[value] => 0
)
[contract_start] => Array
(
[type] => bool
[value] => 0
)
[contract_end] => Array
(
[type] => bool
[value] => 0
)
[T] => Array
(
[type] => clock
[value] =>
)
[a] => Array
(
[type] => int
[value] => 1
)
[candi_ID] => Array
(
[type] => int
[value] => 1
)
[voter_ID] => Array
(
[type] => int
[value] => 1
)
[] => Array
(
[type] =>
[value] =>
)
)
if the value is not equal to existing value an array so I wanna update the value with variable value. This is my code:
$variable = "own=1,contract_start=1";
function updateTheValue($variables,$variable) {
// Split variable looking for into name and value
$vars = explode(",", $variable);
$match = false;
foreach ($vars as $var){
$expbyequal = explode("=", $var);
// If this variable is set
if ( isset($variables [trim($expbyequal[0])]) ) {
// Compare value with stored value
if ( $variables [trim($expbyequal[0])]['value'] == trim($expbyequal[1]) ) {
$match = true;
}else{
$variables[trim($expbyequal[0])] = ["value" => trim($expbyequal[1])]);
$match = false;
}
}
}
return $match;
}
$testing = updateTheValue($variables,$variable);
Any idea will be appreciable.
Your function returns $match
, which could be true
or false
, it doesn't allows you to see your changes.
function updateTheValue(&$variables,$variable) {
// Split variable looking for into name and value
$vars = explode(",", $variable);
$match = false;
foreach ($vars as $var){
$expbyequal = explode("=", $var);
// If this key exists in main keys
if ( in_array(trim($expbyequal[0]), array_keys($variables)) ) {
// Compare value with stored value
if ( $variables [trim($expbyequal[0])]['value'] == trim($expbyequal[1]) ) {
$match = true;
}else{
$variables[trim($expbyequal[0])]["value"] = trim($expbyequal[1]);
$match = false;
}
}
}
return $match;
}
updateTheValue($variables,$variable);
print_r($variables);
With this function you will change data value which key exists in the main keys. You don't need to use $testing
variable, cause reference &
mutates your main array.