search array and get array key - php

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

Related

replace specific array value with another array values in php

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
`

How can I add a value from one array to a new empty associative array in PHP?

I want to count how many times a number exists in my array, but I want to do it like this.
I have an empty array like this:
$aNumberArray = array();
And I have an array like this:
$aArray = (4,4,5,7,4,8,7,9,4,3);
This is my code so far:
foreach ($aArray as $value) {
if (in_array($value, $aNumberArray)) {
// increase value in $aNumerArray.
}else{
// add $value from $aArray to $aNumberArray as key and as value add 1.
}
}
I want to know how I can add the value from $aArray to $aNumberArray as a key and I want to add number 1 as value. When It excist it most increase the value from $aArray.
Here you go:
<?php
$aNumberArray = array();
$aArray = array(4,4,5,7,4,8,7,9,4,3);
foreach ($aArray as $value) {
if (!isset($aNumberArray[$value])) {
$aNumberArray[$value] = 0;
}
$aNumberArray[$value] += 1;
}
print_r($aNumberArray);
Will give you:
Array
(
[4] => 4
[5] => 1
[7] => 2
[8] => 1
[9] => 1
[3] => 1
)
Check output of it
$aArray = [4,4,5,7,4,8,7,9,4,3]; // correct this array format
print_r(array_count_values($aArray));
Output
Array
(
[4] => 4
[5] => 1
[7] => 2
[8] => 1
[9] => 1
[3] => 1
)
Demo
array_count_values — Counts all the values of an array

How do I return a key value by providing another key value in a multidimensional array in PHP?

Assume I have an array like the one below:
Array
(
[0] => Array
(
[town_id] => 1
[town_name] => ABC
[town_province_id] => 7
)
[1] => Array
(
[town_id] => 2
[town_name] => DEF
[town_province_id] => 4
)
[2] => Array
(
[town_id] => 3
[town_name] => GHI
[town_province_id] => 2
)
)
I want to provide value "DEF" in the above array and return value "2".
Please help me.
You can use in_array to get your result.
$input = 'DEF';
foreach($array as $key=>$value){
if(in_array($input,$value)){
$town_id = $value['town_id'];
}
}
print_r($town_id);
You can use array_search with array_column
$key = array_search('DEF', array_column($array, 'town_name'));
Example:
$data = array( array('town_id' => 1, 'town_name' => 'ABC'), array('town_id' => 2, 'town_name' => 'DEF') );
print_r($data);
$key = array_search('DEF', array_column($data, 'town_name'));
print_r($data[$key]['town_id']); // it will have 2
Use array_search and array_column
$key = array_search('DEF', array_column($your_arr, 'town_name'));
$your_arr[$key]['town_id']; // should return DEF
Note: array_column works from PHP 5 >= 5.5.0

Using PHP to extract key from value in an array

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);
?>

explode an array of delimited strings into two arrays

I have the following array:
Array
(
[0] => 10-7
[1] => 11-3
[2] => 11-7
[3] => 12-3
[4] => 12-7
[5] => 13-3
[6] => 13-7
[7] => 14-3
[8] => 14-7
[9] => 15-7
)
that I need to split into two arrays using "-" as delimiter:
Array
(
[0] => 10
[1] => 11
[2] => 11
[3] => 12
[4] => 12
[5] => 13
[6] => 13
[7] => 14
[8] => 14
[9] => 15
)
and
Array
(
[0] => 7
[1] => 3
[2] => 7
[3] => 3
[4] => 7
[5] => 3
[6] => 7
[7] => 3
[8] => 7
[9] => 7
)
Is there anything like array_explode that does what I want? or a combination of php array functions? I'd like to do this without going through my own for/each loop, if possible, or at least minimize having to reinvent the wheel when something (pseudo)in-built is already out there. I already did this with a for loop. But I can't shake the feeling that there's a more elegant way that smartly uses array functions or anything of that kind. Thanks so much, guys.
Additional info:
Not sure if it matters, but I'm actually after the unique values in the resulting two arrays:
Array
(
[0] => 10
[1] => 11
[2] => 12
[3] => 13
[4] => 14
[5] => 15
)
and
Array
(
[0] => 7
[1] => 3
)
The unique values don't need to be sorted, the keys may be preserved or not, and the legal values of the first array range from 0 to 23, while those of the second 1 to 7. However it's possible to have values other than these (0 to 23 and 1 to 7 or even undelimited stray strings or other data types beyond my control), which I would definitely want to throw out.
The magic bullet you're looking for is array_reduce(), e.g. (PHP 5.3+):
list( $left, $right ) = array_reduce( $input,
function( $memo, $item ) {
list( $l, $r ) = explode( '-', $item );
$memo[0][$l] = $memo[1][$r] = true;
return $memo;
},
array( array(), array() )
);
var_dump( array_keys( $left ), array_keys( $right ) );
You can see it in action here.
With PHP <5.3 you'll have to declare the function ahead of time:
function my_reducer( $memo, $item ) {
list( $l, $r ) = // ...
// ... as above ...
}
list( $left, $right ) = array_reduce(
$input, 'my_reducer',
array( array(), array() )
);
http://codepad.org/TpVUIhM7
<?php
$array = array('7-10','7-11','5-10');
foreach($array as $a){list($x[], $y[]) = explode("-", $a);}
print_r(array_unique($x));
print_r(array_unique($y));
?>
Here Is your Solution, Try to implement following code.
Should work for you.
$main_array = array(
'0' => '10-7',
'1' => '11-3',
'2' => '11-7',
'3' => '12-3',
'4' => '12-7',
'5' => '13-3',
'6' => '13-7',
'7' => '14-3',
'8' => '14-7',
'9' => '15-7',
);
foreach($main_array as $key=>$value)
{
$arr_value = explode('-',$value);
$arr_temp1[] = $arr_value[0];
$arr_temp2[] = $arr_value[1];
}
$arr_temp1_unique = array_unique($arr_temp1);
$arr_temp2_unique = array_unique($arr_temp2);
print "<pre>";
print_r($main_array);
print_r($arr_temp1);
print_r($arr_temp2);
print_r($arr_temp1_unique);
print_r($arr_temp2_unique);
print "</pre>";
As far as I know, there is no suitable PHP function that you can use in this situation.
Functions like array_walk() and array_map() result in a single array, not in multiple arrays.
You said you already have tried a sollution with a loop, but for the sake of helping, here is how I would solve this:
//$data contains the array you want to split
$firstItems = array();
$secondItems = array();
foreach($data as $item)
{
list($first, $second) = explode('-', $item, 2);
$firstItems[$first] = true;
$secondItems[$second] = true;
}
//Now you can get the items with array_keys($firstItems) and array_keys($secondItems);
I'm treating the PHP array as a set by setting the keys instead of the values. This makes that you don't have to use array_unique() to get the unique items.
Try:
foreach($old_array as $array){
$new_2d_array = explode('-', $array);
$new_array_1[] = $new_2d_array[0];
$new_array_2[] = $new_2d_array[1];
}
$new_array_1 = array_unique($new_array_1);
$new_array_2 = array_unique($new_array_2);
Okay, if "The unique values don't need to be sorted, the keys may be preserved or not", then I am going to apply the values to the result arrays as both keys and values to ensure uniqueness without any more function calls after the initial loop.
You can use explode() or sscanf(). explode() has a simpler syntax and only requires the glue substring, whereas sscanf() must parse the whole string and therefore needs a more complicated pattern to match with.
If you didn't need uniqueness, you could simply use:
$hours = [];
$days = [];
foreach ($array as $item) {
sscanf($item, '%d-%d', $hours[], $days[]);
}
or
$hours = [];
$days = [];
foreach ($array as $item) {
[$hours[], $days[]] = explode('-', $item);
}
To ensure uniqueness, just use the isolated values as keys as well.
sscanf() allows you to cast the parsed values directly to integers (Demo)
$hours = [];
$days = [];
foreach ($array as $item) {
[0 => $hour, 1 => $day, 0 => $hours[$hour], 1 => $days[$day]] = sscanf($item, '%d-%d');
}
explode() will only produce string-type values. (Demo)
$hours = [];
$days = [];
foreach ($array as $item) {
[0 => $hour, 1 => $day, 0 => $hours[$hour], 1 => $days[$day]] = explode('-', $item);
}
All of the above snippets rely on "array destructuring" syntax instead of calling list(). If you are wondering why the keys are repeated while destructuring, see this post.

Categories