Comparing two arrays with in_array function [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have two array I need to compare with in_array but for some reason it cannot compare, only if I replace manually like this in_array(294, $answer) it shows true.
$answers ----> // Array ( [0] => 294 [1] => 296 )
$answer ---> // Array ( [id] => 294 [question_id] => 87 [correct] => 1 )
in_array($answers, $answer)

It seems you have an answer ($answer = array('id' => 294, 'question_id' => 87, 'correct' => 1 );) identified by id (value 294) and you need to find out if this answer is one of the valid answers whose ids are stored in a list ($answers = array(294, 296);).
The PHP function in_array() is the tool to use, just use it the right way. Search the ID of $answer into the list of IDs stored in $answers:
$answer = array('id' => 294, 'question_id' => 87, 'correct' => 1 );
$answers = array(294, 296);
if (in_array($answer['id'], $answers)) {
echo("Good answer");
} else {
echo("Answer not found in list");
}
Read more about PHP arrays and don't leave that reading until you reach the "Accessing array elements with square bracket syntax" section.

in_array is used to search a string in an array, so you should try to pass a single value from answers array rather than whole array.
For example -
$answers = array(294, 296);
$answer = array('id' => 294, 'question_id' => 87, 'correct' => 1 );
foreach ( $answers as $answer_id ) {
$check = in_array($answer_id, $answer);
echo "<pre>";
var_dump( $check );
echo "</pre>";
}

Related

foreach value with key outside foreach [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a few foreaches which show a total of some numbers.
One of them is this one:
foreach ($lijst['palen'] as $key => $valuepalen)
{
echo $valuepalen ."x Bekaclip palen (48mm / lengte " . $??? . " cm" . "\n";
}
And then there is this one which contains the values I need:
foreach ($optellen as $key => $hoogtevalue)
{
}
The values I need is $hoogtevalue which contains 100 and 110.
But if I insert $hoogtevalue in $??? it only shows the last submitted number 110.
I want to show it like this:
......... lengte is 100
......... lengte is 110
It seems to me that you are trying to map the values from one array to the other, by the position that they sit in the array, rather than by their existing key.
You could use array_map with null as the first parameter to create a new array that consists of pairs from each. (I've added a print_r of the mapped array below to demonstrate the data structure.)
You can then just loop through the pairs.
<?php
$one = [ 63 => 2, 123 => 2];
$two = [ 1 => 100, 3 => 110];
$pairs = array_map(null, $one, $two);
print_r($pairs);
foreach($pairs as $pair)
printf("%d = %d\n", $pair[0], $pair[1]);
Output:
Array
(
[0] => Array
(
[0] => 2
[1] => 100
)
[1] => Array
(
[0] => 2
[1] => 110
)
)
2 = 100
2 = 110
Alternatively you could use the array_values function on both arrays to re-index them and then use keys for association.
This will handle it:
foreach ($lijst['palen'] as $valuepalen) {
foreach ($optellen as $hoogtevalue) {
echo $valuepalen."x Bekaclip palen (48mm / lengte ".$hoogtevalue".cm \n";
}
}

Combining two PHP arrays with some conditional addition thrown in [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've got an unusual problem, but I'm fairly certain it's not impossible to solve.
Consider the two arrays below.
Array ( [0] => 1 [1] => 2 [2] => 2 )
Array ( [0] => 879 [1] => 482 [2] => 1616 )
I need to add the values in second array where the values in the first array are the same so that I would end up with...
Array ( [0] => 879 [1] => 2098 )
How might this be accomplished? Thanks in advance!
This isn't a full-proof way of completing this task, but it achieves the goal you desire. What's happening here is we're looping through your first array (the keys) and using the set values of these keys to add the values from the second array:
$new = array();
foreach($keys as $i => $key) {
if(!isset($new[$key])) { $new[$key] = 0; }
$new[$key] += $vals[$i];
}
Example/Demo
Notes
$keys being your first array: $keys = array(1, 2, 2);
$vals being your second array: array (879, 482, 1616);
As I stated, this isn't full-proof. You will need to modify it to ensure integrity, but it is a start that shows the flow of how you can go about doing what you require.

how to get other elements of an array from associated array when I have a unique value of an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Array
(
[0] => Array
(
[id] => 61
[title] => werwer
)
[1] => Array
(
[id] => 63
[title] => test
)
[2] => Array
(
[id] => 88
[title] => test 2
)
)
How can I get title which has id=63 in above type of array without looping.
Actually, you can't do that without looping. That doesn't mean you have to use loop (foreach/while e t.c.) - but using array functions you will internally iterate array in any case.
For example, in PHP 5.5 that is:
$array = [
['id'=>63, 'title'=>'foo'],
['id'=>65, 'title'=>'bar']
];
//use this - if there are more than 2 connected to `id` fields:
$ids = array_flip(array_column($array, 'id'));//here is iteration, gathering id column
$result = $array[$ids[63]]['title'];
//or else, if `title` is always the only field:
$result = array_column($array, 'title', 'id')[63];
//var_dump($result);
-and so on. array_search() with array_walk() (or similar ways) will hide iteration from you, but it will be done in any case.
Well You can try some crazy stuff like this
array_search(61,
array_combine(
array_map(function ($a) {
return $a['title'];
}, $arr),
array_map(function ($a) {
return $a['id'];
}, $arr)));
but it's highly uneffective (there are 4 loops 'hidden' in 2 array_map, array_combine, and array_search). I advise to use looping - just like #JustAPirate wrote.
$arr = array(array('id' => 61, 'title' => 'werwer'),
array('id' => 62, 'title' => 'asdasd'),
array('id' => 63, 'title' => 'qweqwe'),);
function f($arr, $id) {
foreach ($arr as $a) {
if ($a['id'] == $id)
return $a['title'];
}
}
var_dump(f($arr, 61));
No way to get it without a loop if you don't already know the index of the id 63 in the array.
foreach($array as $element) {
if($element['id'] == 63) {
echo $element['title'];
}
}
You could change the structure of the array:
$array = array(61 => 'werwer', 63 => 'test', 88 => 'test 2');
That would result in:
Array
(
[61] => 'werwer'
[63] => 'test'
[88] => 'test 2'
)
Then you could access/get it with $array[63]

transform array in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How can I transform this array:
Array
(
[0] => 6
[1] => 25
[2] => 29
[3] => 27
[4] => 24
[5] => 7
)
into array a comma separated string list:
6,25,29,27,24,7
without altering the order.
My goal and then I get this string array, but I do not know how to do.
The array is an array already. If you mean you want to turn it into a string, then use the implode function:
$string = implode(",", $array);
The numbers you are seeing first (eg 0 => 6) show the KEY of the element.
You can access individual elements in your code by that key. For example:
echo $array[0];
Would output 6 - the value stored in the element with a key of 0.
Use implode() in php
Try like
$arr = array
(
'0' => 6,
'1' => 25,
'2' => 29,
'3' => 27,
'4' => 24,
'5' => 7
);
$newArr = array();
$newArr[0] = "'".implode("','",$arr)."'";
print_r($newArr);
Output
Array
(
[0] => '6','25','29','27','24','7'
)
implode(',',$array)
Try to print this.

how to loop over this array to obtain only the number 6 and 2? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to loop over the array called $res, but I want to obtain only the values 6 and 2, for each name it is an id, is its with a foreach o just a normal for? I am confused because the array has two arrays insiden and it increments if I add a new name like 'Joe'
$arrayDirectory = array('Nick', 'Alex');
$res = array();
foreach($arrayDirectory as $user) {
$res[] = $obj->obtainID($user);
}
echo print_r($res);
Array ( [0] => Array ( [0] => Array ( [id_usuario] => 6 [0] => 6 ) ) [1] => Array ( [0] => Array ( [id_usuario] => 2 [0] => 2 ) ) ) 1
foreach ($res as $item) {
echo $item[0][0];
}
Or
foreach ($res as $item) {
echo $item[0]['id_usuario'];
}
Depending on what you are looking for
With PHP5.3 you can also use array_map() with a lambda
$idUsarios = array_map(function ($item) {
return $item[0]['id_usario'];
}, $res);
Change
$res[] = $obj->obtainID($user);
to
$user = $obj->obtainID($user);
$res[] = $user[0]['id_usuario'];

Categories