This question already has answers here:
How to check if a specific value exists at a specific key in any subarray of a multidimensional array?
(17 answers)
Closed 3 years ago.
I have an array that looks like this:
$array = array(
array('name' => 'number1', 'number' => '0612345675'),
array('name' => 'number2', 'number' => '0634345675'),
array('name' => 'number3', 'number' => '0634378675')
);
Now I have this number: 0634345675.
How can I check If this number exists in the array $array?
I tried to do this:
if(!in_array('0634345675', $array)){
// insert into DB
}
But this keeps adding multiple of the same rows.
Does anyone knows how to check if this number exists in $array?
Full code:
foreach($DN as $number){ // $DN got ['0634345675', '0632545675', '0614342375']
if(!in_array($number, $array)){
// insert into DB
}
}
You have to use in_array() along with array_column()
<?php
$array = array(
array('name' => 'number1', 'number' => '0612345675'),
array('name' => 'number2', 'number' => '0634345675'),
array('name' => 'number3', 'number' => '0634378675')
);
$valueToFind = '0634345675';
if (in_array($valueToFind, array_column($array, 'number'))){
echo 'found';
}else{
echo 'not found';
}
Output:- https://3v4l.org/TUtSL
If you want to show that array too, then use array_search()
$key = array_search($valueToFind, array_column($array, 'number'));
if($key){
echo 'value found';
echo PHP_EOL;
echo "matched array is";
echo PHP_EOL;
print_r($array[$key]);
}
Output:-https://3v4l.org/Mc2cC
In case multiple match found:
$valueToFind = '0634378675';
$matchedArray = array();
foreach($array as $arr){
if($valueToFind == $arr['number']){
$matchedArray[] = $arr;
}
}
if( count($matchedArray) > 0){
echo "match found";
echo PHP_EOL;
print_r($matchedArray);
}
Output:- https://3v4l.org/p439T
Related
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.
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);
Given array item $array["first level"]["second LVL"], how can I get the key string second LVL itself, not the key-value-pair value?
More Detailed Example
I have an array item variable $array["address"]["city"] that I am passing to a function like so:
<?php
printKey( $array["address"]["city"] );
function printKey( $array_item ) {
return "Output: " . keyValue(array_item);
}
?>
How can I get the key value string city itself from the array item $array["address"]["city"]?
I've seen array_search(), array_keys(), and key(), but none seem to do the trick without a for loop at the least.
EDIT / Clarification:
The problem is, for example, sometimes my function is passed $array["address"]["name"] and sometimes it passes $array["address"]["company"].
I need to be able to dynamically output Name: or Name:
Example function:
$array["address"]["name"] = "Andre";
$array["address"]["company"] = "StackNot";
function printITEMkeyAndValue( $arrayITEM ) {
//It's not possible to do a for loop on just an item, right? It's just a string (?)
return $array_item_key . ": " . $array_item_value;
}
echo printITEMkeyAndValue( $array["address"]["name"] );
echo printITEMkeyAndValue( $array["address"]["company"] );
Desired output:
Name: Andre
Company: StackNot
I understand what you want, but see when you call printKey function with a 2 value, it is not possible to find a key, because array does not exist in the function, the solution is to send the array and your item into the function and find it by search and then get the key.
<?php
$array["address"]["city"] = 2;
function printKey( $array, $item ) {
foreach($array["address"] as $key =>$value){
if ($value == $item){
return "Output: " . $key;
}
}
}
echo printKey($array, $array["address"]["city"]);
See this example
You will have to loop through the entire array to find match with value and get the key for that value using key($array) method
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
In case of 2D array you should pass level 1 element of 2D array.
See if you can do something like this
$arr1d= $array["address"];
while ($val_name = current($array)) {
if ($val_name == '$array_item') {
echo key($array).'<br />';
}
next($array);
}
I think you already passed in second level array key in function
echo printITEMkeyAndValue( $array["address"]["name"] );
so try this if this helpful for you.
function printITEMkeyAndValue( $address, $field_name ){
if( array_key_exists( $field_name, $address ) )
return ucfirst($field_name) .': '.$address[$field_name];
}
$address = array( 'address' => array(
'name' => 'My Name',
'city' => 'My city',
'state' => 'My state',
));
echo printITEMkeyAndValue( $address['address'], 'name' );
echo printITEMkeyAndValue( $address['address'], 'city' );
echo printITEMkeyAndValue( $address['address'], 'state' );
Simply no loop need.
Might be a newbie question but I've been trying to figure this problem and it's doing my head in.
I have the following array :
[0] => Array
(
[provisionalBookingRoomID] => 1
[totalSpecificRoomCount] => 2
)
[1] => Array
(
[provisionalBookingRoomID] => 2
[totalSpecificRoomCount] => 5
)
I need a php function that searches through the array for the value of 'provisionalBookingRoomID' and returns the value of 'totalSpecificRoomCount'
basically something like the following
getProvisionalTotalRoomsCount($currentRoom, $arrayOfRooms);
// getProvisionalTotalRoomsCount('1', $arrayOfRooms) should return 2;
Any ideas?
Check this:
getProvisionalTotalRoomsCount($currentRoom, $arrayOfRooms){
foreach($arrayOfRooms as $key=>$value){
if($value['provisionalBookingRoomID'] == $currentRoom){
return $value['totalSpecificRoomCount'];
}
}
}
For anyone looking for a generic function :
function findValueInArray($array, $searchValue, $searchKey, $requiredKeyValue) {
foreach($array as $key=>$value){
if($value[$searchKey] == $searchValue){
return $value[$requiredKeyValue];
}
}
}
// Usage : findValueInArray($provisionalBookedRoomsArray, '1', 'provisionalBookingRoomID', 'totalSpecificRoomCount');
If you are likely to work with more than one value, you could build a new array with a 1->1 map for those attributes.
<?php
$items = array(
array(
'name' => 'Foo',
'age' => 23
),
array(
'name' => 'Bar',
'age' => 47
)
);
// Php 7
$name_ages = array_column($items, 'name', 'age');
echo $name_ages['Foo']; // Output 23
// Earlier versions:
$name_ages = array();
foreach($items as $value)
{
$name_ages[$value['name']] = $value['age'];
}
echo $name_ages['Foo']; // Output 23
$value = 0;
$array = array(array("provisionalBookingRoomID"=>1,"totalSpecificRoomCount"=>2),array("provisionalBookingRoomID"=>2,"totalSpecificRoomCount"=>5));
array_map(
function($arr) use (&$value) {
if($arr['provisionalBookingRoomID']==1) {
$value = $arr['totalSpecificRoomCount'];
}
},$array
);
echo $value;
This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
Closed 8 years ago.
This the array...
$rt = array(
'0' => array(
'nombre'=>'Jojo',
'fecah'=> '195',
'fch'=>'12'
),
'1' => array(
'nombre'=>'Tito',
'fecah'=> '197',
'fch'=>'13'
),
'2' => array(
'nombre'=>'Jojo',
'fecah'=> '195',
'fch'=>'12'
),
'3' => array(
'nombre'=>'Joji',
'fecah'=> '195',
'fch'=>'12'
),
);
and this is my code:
$a = array();
foreach ($rt as $k=>$v) {
if (in_array($v['nombre'], $a) && in_array($v['fecah'], $a) && in_array($v['fch'], $a) ) {
$a[]=$k;
echo 'The name ' . $v['nombre'] .' is in the array<br>';
} else {
echo 'The name is not in the array <br>';
}
}
so as you can see in the array index [2] the information also exist in the index [0], so I don't need it again, so I need a away to see if the data get repeated or not... if the data is "unique" then build the new array with the "unique" data if the data already exist then jump to next, but I need to compare the 3 keys not just the name... so how do I do that?
You insert array when it is in_array and you use AND
you should reverse your codes like this
$a = array();
foreach ($rt as $k=>$v) {
if (!in_array($v['nombre'], $a) || !in_array($v['fecah'], $a) || !in_array($v['fch'], $a) ) {
$a[]=$k;
echo 'The name ' . $v['nombre'] .' is in the array<br>';
} else {
echo 'The name is not in the array <br>';
}
}
This is you need this
$newarray = array();
foreach($rt as $key => $value)
{
$nombre = $value['nombre'];
if(!isset($newarray[$nombre]))
{
$newarray[$nombre] = $value;
}
}