Hi i am working on some array operations with loop.
I want to compare array key value with the given name.
But i am unable to get exact output.
This is my array :
Array
(
[0] => Array
(
[label] =>
[value] =>
)
[1] => Array
(
[label] => 3M
[value] => 76
)
[2] => Array
(
[label] => Test
[value] => 4
)
[3] => Array
(
[label] => Test1
[value] => 5
)
[4] => Array
(
[label] => Test2
[value] => 6
)
)
This is my varriable which i need to compare : $test_name = "Test2";
Below Code which i have tried :
$details // getting array in this varriable
if($details['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
But every time its returns NotFound.
Not getting what exactly issue.
#Manthan Dave try with array_column and in_array() like below:
<?php
if(in_array($test_name, array_column($details, "label"))){
return $test_name;
}
else
{
return "NotFound";
}
$details is a multidimensional array, but you are trying to access it like a simple array.
You need too loop through it:
foreach ($details as $item) {
if($item['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
}
I hope your array can never contain a label NotFound... :)
You have array inside array try with below,
if($details[4]['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
Although foreach loop should work but if not try as,
for($i=0; $i<count($details); $i++){
if($details[$i]['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
}
Traverse your array like this,
array_walk($array, function($v) use($test_name){echo $v['label'] == $test_name ? $test_name : "NotFound";});
Just use in_array and array_column without use of foreach loop as
if (in_array($test_name,array_column($details, 'label')))
{
return $test_name;
}
else
{
return "NotFound";
}
You need to check only the if condition like below because else meet at first time it will return the "notfound" then it will not execute.
$result = 'NotFound';
foreach ($details as $item) {
if($item['label'] == $test_name)
{
$result = $test_name;
}
}
return $result;
or
$result = 'NotFound';
if (in_array($test_name,array_column($details, 'label')))
{
$result = $test_name;
}
return $result;
Related
If the $gymnast object is not in the $gymnasts array, I add it to my table. However, when I add the same object to the array, in_array() fails (returns 1) and the duplicate object is added to the array. Using print_r, I saw that the $gymnast object is clearly the same as the first element in the $gymnasts array, so why is this happening? How do I fix this?
$gymnasts array
Array ( [0] => Gymnast Object ( [name] => Nastia Liukin [age] => 27 [height] => 5' 3" [olympicYear] => 2008 [medalCount] => 5 [image] => nastia.jpg ) [1] => Gymnast Object ( [name] => Shawn Johnson [age] => 25 [height] => 4' 11" [olympicYear] => 2008 [medalCount] => 4 [image] => shawn.jpg ))
$gymnast object
Gymnast Object ( [name] => Nastia Liukin [age] => 27 [height] => 5' 3" [olympicYear] => 2008 [medalCount] => 5 [image] => nastia.jpg )
index.php
<?php
function isDuplicateEntry($gymnast, $gymnasts) {
foreach ($gymnasts as $gym) {
$gymArr = get_object_vars($gym);
$gymnastArr = get_object_vars($gymnast);
if (count(array_diff($gymnastArr, $gymArr)) == 0) { //gymnast object already exists in array
return true;
}
else {
return false;
}
}
}
//Add gymnast when press add submit button
if(isset($_POST['add'])){
//Set gymnast array to all gymnasts in data.txt
$gymnasts = read_file($filename);
//If form has valid elements & no duplicats, add to data.txt file
if($valid_name && $valid_age && $valid_feet && $valid_inches && $valid_olympicYear && $valid_medalCount && $valid_image){
$gymnast = get_gymnast_from_form();
//Make sure gymnast is not null
if(!is_null($gymnast)){
//Prevent from adding duplicates
if(!isDuplicateEntry($gymnast, $gymnasts)){
//Write task to file
write_file($filename, $gymnast);
//Add gymnast to global var gymnasts array
$gymnasts[] = $gymnast;
echo'<div class ="title">Gymnast Added!</div>';
}
}
}
?>
You cannot use in_array for multidimensional objects straight away. You will have to loop them to find out the match.
Use array_intersect to check if the array is present in another array.
$flag = 0;
foreach ($gymnasts as $gym {
if (count(array_intersect($gymnast, $gym)) == count($gym)) {
echo 'It is present.';
$flag = 1;
break;
}
}
if ($flag == 0) {
echo 'Not present in array';
}
You can also use array_diff to match arrays.
$flag = 0;
foreach ($gymnasts as $gym) {
if (count(array_diff($gymnast, $gym)) == 0) {
echo 'It is present.';
$flag = 1;
break;
}
}
if ($flag == 0) {
echo 'Not present';
}
array_intersect
array_diff
ideone link array_intersect
ideone link array_diff
You can use array_filter with count:
$is_in_array = count(array_filter($gymnasts, function($member) use ($gymnast) {
return $member == $gymnast;
})) > 0;
I have the following array -
Array
(
[31] => Array
(
[0] => 3
[1] => 3
)
[33] => Array
(
[0] => 2
[1] => 1
)
)
Now for the key 31 both of the elements has same value ie 3 but not for the key 33. So I am trying to create another array which will look like.
Array
(
[31] => same
[33] => notsame
)
That means if a key from multidimensional array has got all the values same then it will have the text 'same' else 'notsame'
My code-
foreach($subvaluesArr as $k1=>$v1) //$subvaluesArr is the multidimensional array here
{
foreach($v1 as $k2=>$v2)
{
if($v1[$k2] = $v1[$k2+1])
{
$newArr[$k1] = 'same';
}
else
{
$newArr[$k1] = 'notsame';
}
}
}
echo '<pre>';
print_r($newArr);
echo '</pre>';
And the output is showing 'notsame' for both keys.
Array
(
[31] => notsame
[33] => notsame
)
Any help is highly appreciated.
When you run this snippet, you will get this error
Notice: Undefined index: 2 in /in/bcqEH on line 14
See https://3v4l.org/bcqEH
This is because the code tries to compare first and second, and it tries to compare second and third element. But this third element doesn't exist. This means the comparison fails and sets the value to notsame.
To fix this, you could just compare the first two elements, e.g.
foreach ($subvaluesArr as $k1 => $v1) {
if ($v1[0] == $v1[1]) {
$newArr[$k1] = 'same';
} else {
$newArr[$k1] = 'notsame';
}
}
When you really have more than two elements, you might try array_unique
foreach ($subvaluesArr as $k1 => $v1) {
$u = array_unique($v1);
if (count($u) == 1) {
$newArr[$k1] = 'same';
} else {
$newArr[$k1] = 'notsame';
}
}
You have to break; loop after running the if-else condition.
example :
foreach($subvaluesArr as $k1=>$v1) //$subvaluesArr is the multidimensional array here
{
foreach($v1 as $k2=>$v2)
{
if($v1[$k2] === $v1[$k2+1])
{
$newArr[$k1] = 'same';
}
else
{
$newArr[$k1] = 'notsame';
}
break;
}
}
cant comment so I write it as answer. In your loop when you hit last element of an array, you ask
if($v1[$k2] == $v1[$k2+1])
where $v1[$k2+1] is "undefined" as you are out of bounds. So this last element is always false and you end up with "notsame"
I have this array:
Array
(
[datas] => Array
(
[General] => Array
(
[0] => Array
(
[id] => logo
[size] => 10
)
)
[Rooms] => Array
(
[0] => Array
(
[id] => room_1
[size] => 8
)
[1] => Array
(
[id] => room_2
[size] => 8
)
[2] => Array
(
[id] => room_3
[size] => 8
)
)
)
)
I need to update it when I receive some info like this:
$key = 'room_3';
$toChange = '9';
So in my array, I want to change the size of room_3.
I will always edit the same element (i.e. size).
What I tried:
// Function to communicate with the array
getDatas($array, 'room_3', '9');
function getDatas($datas, $got, $to_find) {
foreach ($datas as $d) {
if (array_search($got, $d)) {
if (in_array($to_find, array_keys($d))) {
return trim($d[$to_find]);
}
}
}
}
But it does not work...
Could you please help me ?
Thanks.
function getDatas($datas, $got, $to_find) {
foreach($datas['datas'] as $key => $rows) {
foreach($rows as $number => $row) {
if($row['id'] == $got) {
// u can return new value
return $row['size'];
// or you can change it and return update array
$datas['dates'][$key][$number]['size'] = $to_find; // it should be sth like $new value
return $datas;
}
}
}
}
function changeRoomSize (&$datas, $roomID, $newSize ){
//assuming that you have provided valid data in $datas array
foreach($datas['datas']['Rooms'] as &$room){
if($room['id'] == $roomID){
$room['size'] = $newSize;
break;//you can add break to stop looping after the room size is changed
}
}
}
//--- > define here your array with data
//and then call this function
changeRoomSize($data,"room_3",9);
//print the results
var_dump($data);
It's a 3-dimensional array, if you want to change the value, do like this:
$key = 'room_3';
$toChange = '9';
$array['datas'] = getRooms($array['datas'], $key, $toChange);
function getRooms($rooms, $key, $toChange) {
foreach($rooms as $k1=>$v1) foreach ($v1 as $k2=>$v2) {
if ($v2['id'] == $key)) {
$rooms[$k1][$k2]['size'] = $toChange;
}
}
return $rooms;
}
print_r($array);
I have an array look like this
$langs = Array
(
[source] => Array
(
[0] => Array
(
[0] => Arabic
)
[1] => Array
(
[0] => Azerbaijani
)
)
[target] => Array
(
[0] => Azerbaijani
[1] => Array
(
[0] => Amharic
[1] => Burmese
)
[2] => Array
(
[0] => English
[1] => German
)
)
)
Now I want to search a value from target key. So I have my code look like this
$target = array();
array_push($target, 'English'); // want to search from the above array so I made it push to array
foreach( $langs['target'] as $langs ) {
if(in_array( $target, $langs )) {
echo 'Got the value';
}
else {
echo 'not got values';
}
}
But its not working. So can someone kindly tell me how to get the values? Any help and suggestions wil be really appreciable. Thanks
You have to do this recursively, iterating through each of the arrays, as in_array does not search recursively.
Try this:
$target = array(
'Azerbaijani',
array('Amharic','Burmese'),
array('English','German')
);
function search_recursive($find, $where) {
foreach ($where as $element) {
if (is_array($element)) {
if (search_recursive($find, $element))
return true;
}
elseif ($find == $element) {
return true;
}
}
return false;
}
if (search_recursive('English', $target)) echo "FOUND";
else echo "Not Found";
This has not been thoroughly tested, so make sure you test properly.
try this:
$got=false;
foreach( $langs['target'] as $lan=> $langs) {
foreach( $langs as $lang=> $lan){
if($target[0]==$lan ) {
$got=true;
break;
}else{
continue;
}
}
}
if($got){
echo "got it";
}else{
echo "not found";
}
NOTE: in_array does not work for multidimensional array.
Ok, I have following 'challange';
I have array like this:
Array
(
[0] => Array
(
[id] => 9
[status] => 0
)
[1] => Array
(
[id] => 10
[status] => 1
)
[2] => Array
(
[id] => 11
[status] => 0
)
)
What I need to do is to check if they all have same [status].
The problem is, that I can have 2 or more (dynamic) arrays inside.
How can I loop / search through them?
array_diff does support multiple arrays to compare, but how to do it? :(
Which ever loop I have tried, or my Apache / browser died - or I got completely bogus data back.
You could just put the problem apart to make it easier to solve.
First get all status items from your array:
$status = array();
forach($array as $value)
{
$status[] = $value['status'];
}
You now have an array called $status you can see if it consists of the same value always, or if it has multiple values:
$count = array_count_values($status);
echo count($count); # number of different item values.
Try this code:
$status1 = $yourArray[0]['status'];
$count = count($yourArray);
$ok = true;
for ($i=1; $i<$count; $i++)
{
if ($yourArray[$i]['status'] !== $status1)
{
$ok = false;
break;
}
}
var_dump($ok);
function allTheSameStatus( $data )
{
$prefStatus = null;
foreach( $data as $array )
{
if( $prefStatus === null )
{
$prefStatus = $array[ 'status' ];
continue;
}
if( $prefStatus != $array[ 'status' ] )
{
return false;
}
}
return true;
}
I'm not sure what you want as output but you could iterate through the outer array and create an output array that groups the inner arrays by status:
$outputArray = array();
foreach ($outerArray as $an_array) {
$outputArray[$an_array['status']][] = $an_array['id'];
}