check if a value exists in array - php

I am trying this code to check if a value exists in an array.
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo (array_key_exists($num, $arr)); //show the index, in this case 1
}
What i want is show the correspondent value, in other words, 0.58
How can i do that ?

What you need is this:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
}

Assuming that you have the key or index position of the value you want, there are two functions that you could use, array_key_exists() or isset().
array_key_exists() checks an array to see if the key you specified exists within the array. It does not check to see if there is a value associated with this key. In other words the key may be set in the array, however the value could be null.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
}
isset() can be used to see if a value is set in a specific array index.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (isset($arr[$num])) {
echo $arr[$num];
}
Since you seem to be asking to only check to see if a specific value exists within an array, you can take a look at using in_array() which will scan the values of the array and return true or false depending on if it found the value.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$needle = '0.58';
if (in_array($needle, $arr)) {
echo "found: $needle";
}
Additionally, php.net has a lot of other array functions that you should familiarize yourself with.

var_dump(in_array(0.58, $arr)); // 3
relevant docs.

Try it
<?php
$arr = array(
'2' => '0',
'3' => '0.58'
);
$num = 3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
// 0.58
}
echo '<br/>';
$val = '0.58';
if (in_array($val, $arr)) {
echo '0.58 found';
}
?>

Related

if a key matched in loop print value in php array

Array (
[category] => abc
[post_tag] => test
[nav_menu] => Home
[link_category] => Link 1
[post_format] => format
)
print conditional value from a loop in php
How can i check if a key is present in this loop
foreach($array as $ar)
{
if($ar->category == 'abc')
{
echo 'found';
}
}
I'm not quite sure what you're trying to find but if it's specific key/value pair it should look like this:
$array = Array (
'category' => 'abc',
'post_tag' => 'test',
'nav_menu' => 'Home',
'link_category' => 'Link 1',
'post_format' => 'format'
);
foreach($array as $key => $value) {
if ($key === 'category' && $value === 'abc') echo 'found', PHP_EOL;
}
Here you just have an associated array that doesn't have any nested arrays.
So if you want to do what you want on this array, you should do something like this:
if (isset($array['category']) && $array['category'] === 'abc') {
echo 'Found!';
}
Using null coalescing operator can make it easier:
if ($array['category'] ?? null === 'abc') {
echo 'Found!';
}
Your question isn't very clear. Do you want to check if a key on an array exists or check if the value exists inside the foreach?
I will try to answer both.
Given that we have this array:
$array = [
'category' => 'abc'
'post_tag' => 'test'
'nav_menu' => 'Home'
'link_category' => 'Link 1'
'post_format' => 'format'
];
If you want to check if a key exists in an array and print the keys value:
if(array_key_exists('category', $array){
echo $array['category']; // prints abc
}
more info about array_key_exists here: array_key_exists
If you want to check if a value exists in the array:
foreach($array as $ar){
if($ar === 'abc'){
echo $ar; // prints abc
}
}
In case you want to check for both of the above:
if(array_key_exists('category', $array) && $array['category'] === 'abc'){
echo $array['category']; // prints abc
}
I hope this helps you figure things out.

How to get a multidimensional array's name?

I'm trying to get the name of an array once I have found a specific value.
Specifically I'm looking to get the highest and lowest values within my array for a certain key, once I have those values I then need to get the name of the array holding those values.
My array looks like this -
Array
(
[123456] => Array
(
[value1] => 0.524
[value2] => 0.898
[value3] => -6.543
)
[246810] => Array
(
[value1] => 0.579
[value2] => 0.989
[value3] => -5.035
)
I have gotten the max value using this code -
max(array_column($statsArr, 'value1'));
This, correctly, gives me the value "0.579". I now need to get the value of the array holding this information so in this case I also want to get the value "246810". I don't know how to do this though, any help would be appreciated!
Iterate over your array with a simple foreach and save required key:
$max = 0;
$founded_key = false;
foreach ($array as $key => $value) {
if ($max < $value['value1']) {
$max = $value['value1'];
$founded_key = $key;
}
}
echo $founded_key, ' - ', $max;
For these kinds of problems I like using array_reduce. max is itself an array reduce operation which takes an array and returns a single value, PHP just offers it out of the box as convenience since it's a very common operation.
Here's an example code:
$array = array(
123456 => array(
'value1' => 0.524,
'value2' => 0.898,
'value3' => -6.543
),
246810 => array(
'value1' => 0.579,
'value2' => 0.989,
'value3' => -5.035
)
);
$maxKey = array_reduce(array_keys($array), function ($carry, $key) use ($array) {
if ($carry === null) {
return $key;
}
return $array[$key]['value1'] > $array[$carry]['value1'] ? $key : $carry;
}, null);
$maxValue = $array[$maxKey]['value1'];
Working example: http://sandbox.onlinephpfunctions.com/code/ecd400ffec91a6436c2fb5ee0410658e22772d4b
function getMax($array, $field) {
$maxValue = null;
$maxKey = null;
foreach($array as $key => $content) {
if (is_null($maxValue) || $content[$field] > $maxValue) {
$maxValue = $content[$field];
$maxKey = $key;
}
}
return [$maxValue, $maxKey];
}
You can search for the maximum value in the array_column.
I first prepare the array_column with correct keys by combining it, then find the max like you do.
Then we can array_search the value.
$value1 = array_combine(array_keys($statsArr), array_column($statsArr, 'value1'));
$max = max($value1);
echo $max . PHP_EOL;
$array = $statsArr[array_search($max, $value1)];
var_dump($array);
https://3v4l.org/Q9gOX
Alternatively you can array_values the $statsArr to make it 0 indexed just like the array_column.
$value1 = array_column($statsArr, 'value1');
$max = max($value1);
echo $max . PHP_EOL;
$array = array_values($statsArr)[array_search($max, $value1)];
var_dump($array);

Print one value from qualifying row or else all values from a specific column

I am using a foreach loop to echo names from my multi-dimensional array.
Sample Array:
$readJson = [
[
'id' => 78,
'name' => 'audi',
'sscat_id' => 59,
'date' => '0000-00-00 00:00:00'
],
[
'id' => 106,
'name' => 'apache',
'sscat_id' => 86,
'date' => '0000-00-00 00:00:00'
],
[
'id' => 16,
'name' => 'asia',
'sscat_id' => 62,
'date' => '0000-00-00 00:00:00'
]
];
I need to implement a condition whereby if the value of $_GET['b'] exists in the id column of my array, I want to echo that subarray's name value.
If $_GET['b'] does not exist in my array, I want to echo all of the name values in the array.
The is my failing code:
foreach ($readJson as $key => $value){
if($_GET["b"] === $value["id"]){ // here is statement
echo $value["name"]; // I want to echo just this item not others
// maybe break; ?
} else {
echo $value["name"]; // echo all items
}
}
I guess I need something like break but I know break won't echo items after it.
Or if I get item index maybe I could echo it by index or id?
A concise approach is a lookup array which is an associative array crafted by array_column() which has id values as keys and name values as values. If there is any drawback yo this approach, it is that there is no short circuiting condition. In other words, array_column() will always iterate the full array to populate the lookup, even if the sought value is in the very first row.
Code: (Demo)
$lookup = array_column($readJson, 'name', 'id');
echo $lookup[$_GET["b"]] ?? implode(', ', $lookup);
Output:
asia
When $_GET['b']=99, then output is:
audi, apache, asia
Another sensible approach would be to never iterate the input array more than once and short circuit when appropriate. You can even populate a result array of one or more names then unconditionally implode the array after the loop is broken or otherwise finished. (Demo)
$names = [];
foreach ($readJson as $row) {
if ($row['id'] === $_GET["b"]) {
$names = [$row['name']]; // overwrite array with single element
break;
}
$names[] = $row['name'];
}
echo implode(', ', $names);
Filter the values by matches, if none matched, use all values instead, and output them:
$values = array_filter($readJson, function ($i) { return $i['id'] == $_GET['b']; });
foreach ($values ?: $readJson as $value) {
echo $value['name'];
}
If $values is empty (== false), $values ?: $readJson falls back to $readJson, otherwise uses $values.
Alternatives might include echo join(', ', array_column($values ?: $readJson, 'name')); depending on what exactly you need to do with those values in the loop.
if(array_search($_GET["b"],array_column($readJson, 'id')) !== False) {
foreach ($readJson as $key => $value){
if($_GET["b"]==$value["id"]){
echo $value["name"];
}
}
}else{
foreach ($readJson as $key => $value){
echo $value["name"];
}
}

PHP: Find last occurence of string in array

I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.
$Data = array(
'0' => 'car',
'1' => 'bike',
'2' => 'bus',
'3' => 'bike',
'4' => 'boat'
);
$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.
I want $key = 3 which is the last matched element.
Any suggestion appreciated.
PHP code demo
<?php
ini_set("display_errors", 1);
$Data = array(
'0' => 'car',
'1' => 'bike',
'2' => 'bus',
'3' => 'bike',
'4' => 'boat'
);
$toSearch="bike";
$index=null;
while($key=array_search($toSearch, $Data))
{
$index=$key;
unset($Data[$key]);
}
echo $index;
Here is the more simple and highly performace way. For it only calculate once, you can access it many time. The live demo.
$data = array_flip($Data);
echo $data['bike'];
after the flip, only keep the last element of the same elements. Here is the print_r($data)
Array
(
[car] => 0
[bike] => 3
[bus] => 2
[boat] => 4
)
We can use array_reverse to reverse array.
$key = array_search('bike', array_reverse($Data,true));
It will return 3.
you can use krsort to sort the array by key.
krsort($Data);
$key = array_search('bike', $Data);
echo $key;
Working example: https://3v4l.org/fYOgN
For this I am created one function it is very easy to use. You can pass only array and parameters.
function text_to_id($value, $arr_master) {
$id_selected = 0;
$search_array = $arr_master;
if (in_array($value, $search_array)) {
$id_selected = array_search($value, $search_array);
// pr($id_selected);exit;
}
if (!$id_selected) {
foreach ($search_array as $f_key => $f_value) {
if (is_array($f_value)) {
if (in_array($value, $f_value)) {
$id_selected = $f_key;
break;
}
} else if ($value == $f_value) {
$id_selected = $f_key;
break;
}
else;
}
}
return $id_selected;
}
this function use like this
$variable = text_to_id('bike', $your_array);

Compare single array value

How can I do a comparison when my array returns value with index.
Returned value is Array ( [isMember] => 0 ) and I want do to a comparison on the value only
if ($memberStatus == 0)
{
print_r($memberStatus);
}
Explanation
Index Array's value can be access by using corresponding index value where as an Associative Array's value can be access by using corresponding key along with array name and in between square brackets that is
arrayName["index-value"]
or
arrayName["key-name"].
You may refer to the following code.
Code
//For Associative Array
$arrayOne = array(
'keyone' => 'a',
'keytwo' => 'b',
'keythird' => 'c'
);
if ($arrayOne['keyone'] == 'a') {
print_r($arrayOne['keyone']);
//output a
}
OR
//For Index Array
$arrayOne = array('a', 'b', 'c');
if ($arrayOne[0] == 'a') {
print_r($arrayOne[0]);
//output a
}
If you have an array like this:
$data = [ 'isMember' => 0, 'data1' => 1, 'data2' => 2 /* ... */ ];
You can access single elements by using the name of the array and write the key in square brackets:
// change isMember to whatever key-value pair you need
$memberStatus = $data['isMember'];
if ($memberStatus === 0)
{
print 'user is a member';
}
else
{
print 'user it not a member';
}
I think what you are looking for is:
$myArray = array(
'isMember' => 0
);
if ( $myArray['isMember'] == 0 ) {
print_r($myArray['isMember']);
}
Are you looking for a key inside an array? Then you need:
echo array_key_exists(9, [1=>'nope',2=>'nope',3=>'nope',9=>'yah']) ? 'Yes it does' : 'it doesn\'t';
Otherwise you are looking for:
echo in_array("my value", ["my value", "a wrong value", "another wrong one"]) ? 'yush' : 'naaaaah';
Either way you can use both in a if statement rather than a thernary operator.
I am not sure which type of array you need to compare because there are generally 2 different types of them:
Indexed
- You pick numerical index which do you want to compare
$array = array("admin", "moderator", "user");
if ($array[0] == "user") {
// CODE
}
Associative
- You pick the string key which do you want to compare
$array = array( "id1" => "member", "id2" => "not member","id3" => "user");
if ($array["id2"] == "not member") {
// CODE
}

Categories