I have a PHP array that prints the following information:
Array (
[0] => 23
[1] => 34
[2] => 35
[3] => 36
[4] => 37
[5] => 38
..<snip>..
)
I have the value and would like to cross reference it with the array to return a key. For instance, if I have a variable $value = 34 I would want to run a PHP function to return the key, which in this case is 1.
To be more specific, the array is stored in variable $pages and the value is stored in variable $nextID. I tried using array_search with no luck:
How do I go about this?
array_search is exactly what you're looking for. I'm not sure how you had problems with it.
$arr = [
5,
10,
15,
20
];
$value = 15;
echo array_search($value, $arr); // 2
You could use foreach() like that:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
function mySearch($array, $search){
foreach($array as $key => $value){
if($value == $search){
return $key;
}
}
}
echo mySearch($arr, 3);
?>
Related
This question already has answers here:
Push elements from one array into rows of another array (one element per row)
(4 answers)
Closed 5 months ago.
I need to evenly/synchronously push values from my second array into the rows of my first array.
The arrays which have the same size, but with different keys and depths. The first is an array of rows and the second is a flat array.
$array1 = [
12 => [130, 28, 1],
19 => [52, 2, 3],
34 => [85, 10, 5]
]
$array2 = [4, 38, 33]
Preferred result:
[
12 => [130, 28, 1, 4],
19 => [52, 2, 3, 38],
34 => [85, 10, 5, 33]
]
(I would like to keep the same indices of array 1, however it is not mandatory.)
I have tried these methods, but none of them work because the first array keys are unpredictable.
$final = [];
foreach ($array1 as $idx => $val) {
$final = [$val, $array2[$idx]];
}
Another:
foreach ($array1 as $index => $subArray) {
$array1 [$index][] = $array2[$index];
}
Here is one way to do this:
$merged = array_map('array_merge', $array1, array_chunk($array2, 1));
$result = array_combine(array_keys($array1), $merged);
The second step with array_combine is necessary to reapply the non-sequential keys because array_map won't preserve them in the first step.
An example using foreach
<?php
$a = [
2 => [130, 28, 1, 1, 6],
3 => [52, 2, 3, 3, 27]
];
$b = [5, 38];
$output = [];
$idx = 0;
foreach ($a as $key => $value) {
$value[] = $b[$idx];
$output[$key] = $value;
++$idx;
}
print_r($output);
Sandbox HERE
You can loop $array1 using a foreach to get the current key $index
Get the value from $array2 by using a counter as the array key which, is incremented by 1 for every iteration.
Then add the value to the end of the current array.
$array1 = [
2 => [130, 28, 1, 1, 6],
3 => [52, 2, 3, 3, 27],
13 => [41, 20, 27, 13, 37]
];
$array2 = [89, 99, 109];
$counter = 0;
foreach ($array1 as $index => $subArray) {
$array1[$index][] = $array2[$counter++];
}
print_r($array1);
Output
Array
(
[2] => Array
(
[0] => 130
[1] => 28
[2] => 1
[3] => 1
[4] => 6
[5] => 89
)
[3] => Array
(
[0] => 52
[1] => 2
[2] => 3
[3] => 3
[4] => 27
[5] => 99
)
[13] => Array
(
[0] => 41
[1] => 20
[2] => 27
[3] => 13
[4] => 37
[5] => 109
)
)
See a PHP demo.
Maintaining a counter while iterating is a simple way of accessing second array values while iterating the first. It is not necessary to make multiple passes of the arrays, just one iteration is all that is required.
Codes: (Demos)
a mapper:
$i = -1;
var_export(
array_map(fn($row) => array_merge($row, [$array2[++$i]]), $array1)
);
a looper:
$i = -1;
foreach ($array1 as &$row) {
array_push($row, $array2[++$i]);
}
var_export($array1);
a walker:
$i = -1;
array_walk($array1, fn(&$row, $k) => array_push($row, $array2[++$i]));
var_export($array1);
If you don't care about preserving the first array's keys in the result array, then you can simply use:
var_export(
array_map('array_merge', $array1, array_chunk($array2, 1))
);
my 1st array values are
Array (
[0] => abc
[1] => xyz
[2] => Other
[3] => Other
[4] => pqr )
when array contains value as Other i want to replace that with below array
Array (
[0] => lmnsa
[1] => asda )
I want to do this in PHP. any help guys?
First loop over the array1 and test for the value 'Other', if found replace the value with your array2
Note the use of &$a to make the $a from the foreach loop a reference, so that it can be used to replace the original array occurance and not a copy of the array which woudl have been the result without the use of the &
$array1 = Array ( "abc","xyz","Other", "Other", "pqr" );
$array2 = Array ( "lmnsa", "asda" );
foreach ($array1 as &$a) {
if ( $a == 'Other') {
$a = $array2;
}
}
print_r($array1);
The RESULT
Array
(
[0] => abc
[1] => xyz
[2] => Array
(
[0] => lmnsa
[1] => asda
)
[3] => Array
(
[0] => lmnsa
[1] => asda
)
[4] => pqr
)
I don't really understand what result are you looking for.
If you want to just replace elements with value 'Other' with some different value:
$newValue = 'New value instead of Other';
// $newValue = ['abc' 'def']; <-- if you want to replace string by an array. It wasn't unclear what you expect to achieve from the question.
$array = ['a', 'b', 'Other', 'c', 'Other', 'd'];
foreach ($array as $idx => $element) {
if ($element === 'Other') {
$array[$idx] = $newValue;
}
}
Or if you have an array of replacements, which must gradually replace all 'Other' values:
$array = ['a', 'b', 'Other', 'c', 'Other', 'd'];
$replacements = ['New Value 1', 'New Value 2'];
$replacementIdx = 0;
foreach ($array as $idx => $element) {
// Always check if you were not run out of replacement values
if (!isset($replacements[$replacementIdx])) {
break;
}
if ($element === 'Other') {
$array[$idx] = $replacements[$replacementIdx++];
}
}
Instead of using foreach ($array as $key => $value) you may also try to replace elements by reference (see RiggsFolly answer)
Based on your request what Yamingue stated is correct. You may need to clarify what you want. Are you attempting to say if the indexed value of the array initial array is 2 and its value is "Other" to replace it with it with the equivalent value of another array with the same index number?
Its been a while since ive done php buy lets give this a go.
$array1 = Array (
0 => "abc"
1 => "xyz"
2 => "Other"
3 => "Other"
4 => "pqr" );
$array2 = Array (
0 => "lmnsa"
1 => "asda"
2 => "thg"
3 => "ris"
4 => "slrn");
Foreach($array1 as $arr1key => $arr1val) {
If($arr1val == "Other"){
$array1[$arr1key] = $array2[$arr1key];
}
}
You may need to unset the values however as i said been a while for me. Nowbif you want to embed the 2nd array into the value of the first array where it currently says other thats another story, each language is a little different on multidimensional and nested arrays so i cant speak to it.
there are several ways to do it as needed. the first is to replace it with another array like this
`
$array1 = Array (
0 => "abc"
1 => "xyz"
2 => "Other"
3 => "Other"
4 => "pqr" );
$array2 = Array (
0 => "lmnsa"
1 => "asda" );
$array1 = $array2
`
I have a multidimensional array:
$array =
Array (
[0] => Array ( [id] => 2 [zoneId] => 2 [buildingId] => 2 [typeId] => 2 )
[1] => Array ( [id] => 4 [zoneId] => 2 [buildingId] => 2 [typeId] => 1 )
[2] => Array ( [id] => 6 [zoneId] => 6 [buildingId] => 17 [typeId] => 2 ) )
And I would like to search if the combination of, for example, [buildingId] => 2, [typeId] => 2 exists is array 0, 1 or 2.
I tried the following:
$keyType = array_search(2, array_column($array, 'typeId'));
$keyBuilding = array_search(2, array_column($array, 'buildingId'));
if(is_numeric($keyType)&&is_numeric($keyBuilding)){
echo 'Combination does exists'
}
This works, but gives also a false positive if I would search for [buildingId] => 17, [typeId] => 1. How can I solve this?
edit
I would also like to know if a combination is not in the array, how can I arrange that?
if($result == false){
echo 'does not exists';
}
You can try this code:
$keyTypeExistsAndHaveSameValue = isset($array['typeId']) && $array['typeId'] === 2;
$keyBuildingExistsAndHaveSameValue = isset($array['buildingId']) && $array['buildingId'] === 2;
if($keyTypeExistsAndHaveSameValue && $keyBuildingExistsAndHaveSameValue){
echo 'Combination does exists'
}
This code check if typeId & buildingId keys exist but it also check if its values are 2 and 2.
$buildingId = 2;
$typeId = 2;
$result = false;
foreach ($array as $key => $val) {
if ($val['buildingId'] == $buildingId && $val['typeId'] == $typeId) {
$result = $key; // If you want the key in the array
$result = $val; // If you want directly the entry you're looking for
break; // So that you don't iterate through the whole array while you already have your reuslt
}
}
I think what you need is this
$keyType = array_search(1, array_column($array, 'typeId'));
$keyBuilding = array_search(17, array_column($array, 'buildingId'));
if(is_numeric($keyType)||is_numeric($keyBuilding)){
echo 'Combination does exists';
}
Now here you need or operator instead of and operator because you want either typeid = 1 exists or building id = 17 exists.
If I have understand your question correctly then you are trying to do something like this, right ?
Hope this helps!
You would need to do a foreach loop to get the actual array number, the other solution don't seems to answer what you're looking for, which is to get the index number.
I would like to search if the combination of, for example, [buildingId] => 2, [typeId] => 2 exists is array 0, 1 or 2.
EDIT: This code is just sample code to show how you would get the array index number, in a production environment you would save the matching arrays, comparison figures are not hard coded, etc...
$array = array(array('id' => 2, 'zoneId' => 2, 'buildingId' => 2, 'typeId' => 2),
array('id' => 4, 'zoneId' => 2, 'buildingId' => 2, 'typeId' => 2),
array('id' => 6, 'zoneId' => 6, 'buildingId' => 17, 'typeId' => 2));
foreach ($array as $building => $building_details)
{
if ($building_details['buildingId'] === 2 && $building_details['typeId'] === 2)
{
echo 'Array number ' . $building . ' matches criteria<br>';
}
}
Output:
Array number 0 matches criteria
Array number 1 matches criteria
You can view this snippet online here.
I have an array of some values which I need to convert to new array and sum every value with all previous values. For example (array length, keys and values always differ), this is what I have:
Array
(
[0] => 1
[1] => 1
[2] => 5
[3] => 1
[4] => 1
[7] => 1
[8] => 3
[9] => 1
)
and this is what I need:
Array
(
[0] => 1
[1] => 2
[2] => 7
[3] => 8
[4] => 9
[7] => 10
[8] => 13
[9] => 14
)
I tried many different ways but always stuck at something or realized that I'm wrong somewhere. I have a feeling that I'm trying to reinvent a wheel here, because I think there have to be some simple function for this, but had no luck with finding solution. This is last way I tried:
$array = array( "0"=> 1, "1"=> 1, "2"=> 5, "3"=> 1, "4"=> 1, "7"=> 1, "8"=> 3, "9"=> 1 );
$this = current($array);
$next = next($array);
$end = next(end($array));
$sum = 0;
$newArray = array();
foreach ($array as $val){
if($val != $end){
$sum = ($this += $next);
array_push($newArray, $sum);
}
}
print_r($newArray);
..unfortunately wrong again. I spend lot of time finding ways how not to get where I need to be, can someone kick me into right direction, please?
Suggest you to use array_slice() & array_sum()
$array = array( "0"=>1,"1"=>1,"2"=>5,"3"=>1,"4"=>1,"7"=>1,"8"=>3,"9"=>1);
$keys = array_keys($array);
$array = array_values($array);
$newArr = array();
foreach ($array as $key=>$val) {
$newArr[] = array_sum(array_slice($array, 0, $key+1));
}
$newArr = array_combine($keys, $newArr);
print '<pre>';
print_r($newArr);
print '</pre>';
Output:
Array
(
[0] => 1
[1] => 2
[2] => 7
[3] => 8
[4] => 9
[7] => 10
[8] => 13
[9] => 14
)
Reference:
array_slice()
array_sum()
array_combine()
array_keys()
let assume your array variable is $a;
You can use simple for loop
for($i=1;$i<sizeof($a);$i++)
{
$a[$i]=$a[$i]+$a[$i-1];
}
You can just go over the array sum and add to a new array (in a simple way):
$array = array( "0"=> 1, "1"=> 1, "2"=> 5, "3"=> 1, "4"=> 1, "7"=> 1, "8"=> 3, "9"=> 1 );
var_dump($array);
$newArray = array();
$sum = 0;
foreach ($array as $a){
$sum += $a;
$newArray[]=$sum;
}
var_dump($newArray);
$sums = array_reduce($array, function (array $sums, $num) {
return array_merge($sums, [end($sums) + $num]);
}, []);
In other words, this iterates over the array (array_reduce) and in each iteration appends (array_merge) a number to a new array ($sums) which is the sum of the previous item in the array (end($sums)) and the current number. Uses PHP 5.4+ array syntax ([]).
You complicated too much. Loop trough all elements of array and add current element to sum. Then assign that sum to new array.
$array = array( "0"=> 1, "1"=> 1, "2"=> 5, "3"=> 1, "4"=> 1, "7"=> 1, "8"=> 3, "9"=> 1 );
$sum = 0;
$newArray = array();
foreach ($array as $key=>$val){
$sum += $val;
$newArray[$key]=$sum;
}
Make sure to get indexes right.
I have an array, which I'd like to search for a value in and retreive the array key if it exists, but not sure how to even go about doing that. Here's my array:
Array
(
[hours] => Array
(
[0] => 5
[1] => 5
[2] => 6
[3] => 6
[4] => 8
[5] => 10
)
)
So I'd like to search the hours array for 10, if 10 exists in the array, I want the key (5) to be returned. If that makes sense?
Am trying to do it dynamically so the search string (10) will change, but I figure if I can get it working for number 10, I can get it working with a variable number :)
array_search is what you need.
$var = 10;
$key = array_search($var, $hours);
$key = array_search($array, 10);
Use the function array_search
$key = array_search(10,$aray); // $key will get 5 in your case.
the syntax is:
key = array_search(value_to_search,array);
Syntax : array_search ( Search Keyword here , Array here);
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1