If key exist into a multidimensional array - php

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

Related

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

How to check PHP array for key then assign value?

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;
}
}

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.

php - Find array for which a key have a given value

I have an array of dictionnaries like:
$arr = array(
array(
'id' => '1',
'name' => 'machin',
),
array(
'id' => '2',
'name' => 'chouette',
),
);
How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?
Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.
Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).
As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
1 => 'machin',
2 => 'chouette',
);
This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.
$name;
foreach ($arr as $value){
if ( $value['id'] == 2 ){
$name = $value['name'];
break;
}
}
I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }
The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');
Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
if($value == "machin"){
return $key;
}
}
But of course the same would work with your old array:
foreach($arr as $item){
if($item['name'] == "machin"){
return $item['id'];
}
}
It depends on what you are planning to do with the array ;-)
array_key_exist() is the function to check for keys. foreach will help you get down in the multidimensional array. This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
foreach($bigArray as $array) {
if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
return $array['name'];
}
}
return false;
}
//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"
It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
if($v['id'] == '2') {
$name = $v['name'];
break;
}
}
echo $name;
So no, you are not forced to reindex the array, but it would make things easier.

Checking if all the array items are empty PHP

I'm adding an array of items from a form and if all of them are empty, I want to perform some validation and add to an error string. So I have:
$array = array(
'RequestID' => $_POST["RequestID"],
'ClientName' => $_POST["ClientName"],
'Username' => $_POST["Username"],
'RequestAssignee' => $_POST["RequestAssignee"],
'Status' => $_POST["Status"],
'Priority' => $_POST["Priority"]
);
And then if all of the array elements are empty perform:
$error_str .= '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';
You can just use the built in array_filter
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
So can do this in one simple line.
if(!array_filter($array)) {
echo '<li>Please enter a value into at least one of the fields regarding the request you are searching for.</li>';
}
Implode the array with an empty glue and check the size of the resulting string:
<?php if (strlen(implode($array)) == 0) echo 'all values of $array are empty'; ?>
Please note this is a safe way to consider values like 0 or "0" as not empty. The accepted answer using an empty array_filter callback will consider such values empty, as it uses the empty() function. Many form usages would have to consider 0 as valid answers so be careful when choosing which method works best for you.
An older question but thought I'd pop in my solution as it hasn't been listed above.
function isArrayEmpty(array $array): bool {
foreach($array as $key => $val) {
if ($val !== '' || $val !== null) // remove null check if you only want to check for empty strings
return false;
}
return true;
}
you don't really need it.
You're going to validate these fields separately and by finishing this process you can tell if array was empty (or contains invalid values, which is the same)
simplify use this way:
$array = []; //target array
$is_empty = true; //flag
foreach ($array as $key => $value) {
if ($value != '')
$is_empty = false;
}
if ($is_empty)
echo 'array is empty!';
else
echo 'array is not empty!';
I had the same question but wanted to check each element in the array separately to see which one was empty. This was harder than expected as you need to create the key values and the actual values in separate arrays to check and respond to the empty array element.
print_r($requestDecoded);
$arrayValues = array_values($requestDecoded); //Create array of values
$arrayKeys = array_keys($requestDecoded); //Create array of keys to count
$count = count($arrayKeys);
for($i = 0; $i < $count; $i++){
if ( empty ($arrayValues[$i] ) ) { //Check which value is empty
echo $arrayKeys[$i]. " can't be empty.\r\n";
}
}
Result:
Array
(
[PONumber] => F12345
[CompanyName] => Test
[CompanyNum] => 222222
[ProductName] => Test
[Quantity] =>
[Manufacturer] => Test
)
Quantity can't be empty.
this is pretty simple:
foreach($array as $k => $v)
{
if(empty($v))
{
unset($array[$k]);
}
}
$show_error = count($array) == 0;
you would also have to change your encapsulation for your array values to double quotes.

Categories