How to check PHP array for key then assign value? - php

Say I have an array called $myarray like this...
[187] => 12
[712] => 24
Within a loop later in my code, i want to check to see if a key exists in that array and if it does, i want to assign the corresponding value to a variable.
So I'd check like this...
if (array_key_exists($id), $myarray)) {
$newvariable= "(the value that goes with the index key)";
} else {
$newvariable="";
}
So if it checked for key "187", then $newvariable would be assigned "12";
I guess I just need to know what to replace "(the value that goes with the index key)" with. Or maybe I'm approaching it wrong?

Just use the value of $id as key:
if (array_key_exists($id, $myarray)) {
$newvariable= $myarray[$id];
} else {
$newvariable="";
}

<?php
$myArr = [187 => 12, 712 => 24];
foreach($myArray as $key => $value)
{
if($key == 187) {
$newVariable = $value;
}
}

Related

If key exist into a multidimensional array

I have this array:
$modules = array(
'module1' => array(
'position' => 2
)
);
How I can check that module1 exist and how to get the position number ?
Thanks a lot.
You can use array_key_exists() function
Code
if (array_key_exists("module1", $modules)) {
echo $modules["module1"]["position"]
}
else {
echo "module1 doesn't exist in the array"
}
Hope this helps ;)
To check if a value exists in an array, you can use array_key_exists (value, $ array).
To get the value of this array you must use $array[key][value]. An example is in the case below, where it checks whether the key exists, if it exists prints the value, if there is no exists then print that was not found:
$modules = array(
'module1' => array(
'position' => 2
)
);
$value = 'module1';
if(array_key_exists($value, $modules)) {
echo $modules[$value]['position'];
} else {
echo 'not found';
}
The variable $value may receive the value of you want to fetch. Or you can replace the place where it appears with value you want to fetch.
Use isset function to get it
if(isset($modules['module1']) && isset($modules['module1']['position'])) {
$value = $modules['module1']['position'];
}
Hope this will work
$module['module1']['position']=2;
foreach($module as $index=>$item){
foreach($item as $i){
if($index=='module1'){
echo $i;
}
}
}
Above code help you to determine key value and you can implement your logic arbitrarily

PHP Unset Command in If Statement Not Working

I would like to unset an HTTP Posted key from the array after it echoes the "1" result, but the unset doesn't seem to work. How can I fix this?
$keylist = array('HHH', 'GGG');
if (in_array($_POST["keys"], $keylist)){
echo "1";
unset($keylist[$_POST["keys"]]);
} else {
echo "0" ;
}
Appreciate any help,
Hobbyist
Your unsetting $keylist not $_POST
unset($_POST["keys"]);
You're using the wrong array key for unsetting (You're trying to unset $keylist["HHH"], not, say, $keylist[0]) - you'll need to retrieve the key from the array, and then unset that specifically in order to remove it from the keylist.
$index = array_search($_POST["keys"], $keylist);
if($index!==false) { //YES, NOT DOUBLE EQUALS
unset($keylist[$index));
}
If $_POST["keys"] is an array of keys, you'll need to use array_keys with a search_value instead.
Array_search documentation: http://php.net/manual/en/function.array-search.php
Array_keys documentation: http://php.net/manual/en/function.array-keys.php
EDIT: Adding a full, working example.
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
if(in_array($_POST["keys"], $keylist)) {
$indexToRemove = array_search($_POST["keys"], $keylist);
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Another example, this time checking the index itself to see if it is not false:
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
$indexToRemove = array_search($_POST["keys"], $keylist);
if($indexToRemove!==false) {
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Output:
1Array ( [0] => asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh [1] => derp2 ) Array ( [1] => derp2 )
I realize now that I only had one = on the $index!==false check - the reason you need two is because $index is 0 if you're removing the first element of an array. Per PHP documentation,
Warning
This function may return Boolean FALSE, but may also return a non-Boolean
value which evaluates to FALSE. Please read the section on Booleans for more
information. Use the === operator for testing the return value of this function.
in_array($_POST["keys"], $keylist) checks if the posted value $_POST["keys"] is present as a value in $keylist, but unset($keylist[$_POST["keys"]]) uses $_POST["keys"] as the key in $keylist to unset something.
Since in_array() returns true, the posted value is present in the array $keylist. But you can't do unset($keylist['GGG']) because that value is not set.
A simple solution is to use the same values as keys too:
$keylist = array('HHH', 'GGG');
$keylist = array_combine($keylist, $keylist);
More about array_combine().
Your array have keys. So "HHH" in keylist is $keylist[0] and not $keylist['HHH']. You can not unset it because you have to define the array key instead of the array value.
Try to search for the array value like this:
array_search($_POST["keys"], $keylist)
This will return the array key for you or false if its not found. Your full code should like look like:
echo "1";
$arrkey = array_search($_POST["keys"], $keylist);
if( $arrkey !== false ){
unset($keylist[$arrkey]);
}
Here the PHP Manual for the array_search function: http://php.net/manual/en/function.array-search.php

PHP Array reference, modifying array values

I'm trying to modify an array when looping through it and increment certain values.
$data = ['traits' => [[['amt' => 1]]]];
var_dump($data['traits']);
foreach ($data['traits'] as $key => &$index) {
foreach ($index as $key => &$value) {
$value['amt'] = $value['amt']++; // This should increment
if (in_array($key, $input)) {
$i++;
$insert["field_".$i] = $key."_1";
}
}
}
var_dump($data['traits']); // SAME AS PREVIOUS VAR_DUMP
What you are doing in the loop is undefined:
$value['amt'] = $value['amt']++;
The outcome of that depends on what's evaluated first. In this case $value['amt']++ seems to be evaluated first and then assigned to $value['amt'] again; the side effect of the increment is lost.
On the other hand, the following statement will work as expected:
$value['amt']++;

Get the key of an array "value" for use in a function

I have an array defined:
$flatdata["body_font-family"] = "Arial";
I want to use that array value in a function:
function display_name($input) {
showmethekeyofthearrayvalue($input); // how can I get the key name here?
}
echo display_name($flatdata["body_font-family"]);
So that the output is:
body_font-family
You may try like this:
key($arr);
This will return the key name
From the manual
key() returns the index element of the current array position.
Or you may try to use array_search
$arr = array ('key1' => 'a', 'key2' => 'b', );
$key = array_search ('a', $arr);
What about this?
function display_key($array, $val) {
while($array_pos = current($array)) {
if($array_pos == $val) {
return key($array);
}
}
}
echo display_key($flatdata, $flatdata["body_font-family"]);
I'm assuming displaykey is supposed to be display_name in your example.
If so, you won't be able to return the key by passing in an array element such as $flatdata["body_font-family"] because in this case you're only passing in a specific string i.e. Arial, so the function doesn't have any info about the key.

Find value of key where value of another key equals matched value (associative array)

For example, I have an array of:
array(
array(
['make']=>ford
['color']=>blue
['type']=>automatic
),
array(
['make']=>chevrolet
['color']=>red
['type']=>manual
)
Is is possible to find in PHP the value of a known key when all I have to go on is the value of another key?
Say for example, I have the value "blue" and I know that it's in the "color" key, can I now find what the value of "car" is from this information?
The known value of the known key is unique. (in this example, there couldn't be two values of "blue")
I hope this makes sense, and thanks in advance for your help.
$knownColor = 'blue';
$knownKey = 'color';
$desiredKey = 'make';
foreach ($outerArray as $inner) {
if ($inner[$knownKey] == $knownColor) {
$result = $inner[$desiredKey];
// or to get the whole inner array:
// $result = $inner;
break;
}
}
var_dump($result);
Assuming your array is assigned to $cars it would go something like this:
$knownColor = 'blue';
$knownKey = 'color';
...
foreach ($cars as $car) {
if ($car[$knownKey] === $knownColor) {
return $car;
}
}

Categories