Suppose I have an array like this:
$array = array("a","b","c","d","a","a");
and I want to get all the keys that have the value "a".
I know I can get them using a while loop:
while ($a = current($array)) {
if ($a == 'a') {
echo key($array).',';
}
next($array);
}
How can I get them using a foreach loop instead?
I've tried:
foreach ($array as $a) {
if ($a == 'a') {
echo key($array).',';
}
}
and I got
1,1,1,
as the result.
If you would like all of the keys for a particular value, I would suggest using array_keys, using the optional search_value parameter.
$input = array("Foo" => "X", "Bar" => "X", "Fizz" => "O");
$result = array_keys( $input, "X" );
Where $result becomes
Array (
[0] => Foo
[1] => Bar
)
If you wish to use a foreach, you can iterate through each key/value set, adding the key to a new array collection when its value matches your search:
$array = array("a","b","c","d","a","a");
$keys = array();
foreach ( $array as $key => $value )
$value === "a" && array_push( $keys, $key );
Where $keys becomes
Array (
[0] => 0
[1] => 4
[2] => 5
)
You can use the below to print out keys with specific value
foreach ($array as $key=>$val) {
if ($val == 'a') {
echo $key." ";
}
}
here's a simpler filter.
$query = "a";
$result = array_keys(array_filter($array,
function($element)use($query){
if($element==$query) return true;
}
));
use
foreach($array as $key=>$val)
{
//access the $key as key.
}
Related
i have an $arrays array like this :
Array
(
[0] => Array
(
[0] => VUM
[1] => UA0885
)
[1] => Array
(
[0] => VUA
[1] => UA0885
)
)
i want to check if input value exist (VUA & UA0885), than not add it to this array.
Ex:
(VUA & UA0885) => not add
(VUB & UA0885) => add
(VUA & UA0886) => add
here is my code:
foreach($arrays as $array){
if($array[0] != $_REQUEST['tourcode'] || $array[1] != $_REQUEST['promocode']){
$arrays[] = array($_REQUEST['tourcode'],$_REQUEST['promocode']);
}
}
Tried use in_array too but it still add a duplicate to $arrays
You can iterate the array, check if the same values are found, and if not push the new values:
$tour = $_REQUEST['tourcode'];
$promo = $_REQUEST['promocode'];
$new = true; //default to true
foreach($arrays as $el){
if($el[0].'-'.$el[1] == $tour. '-' .$promo]){
$new=false;
break; //no need to continue
}
}
if($new) $arrays[]=[$tour,$promo];
foreach($arrays as $key => $array) {
if($array[0] == $_REQUEST['tourcode'] && $array[1] == $_REQUEST['promocode']) {
unset($arrays[$key]);
}
}
To check if there is an entry with tourcode AND promocode already in the array you can use something close to what you had:
function codeInArray($array, $tourcode, $promocode) {
foreach ($array as $entry) {
// check if we have an entry that has the same tour and promo code
if ($entry[0] == $tourcode && $entry[1] == $promocode) {
return true;
}
}
return false;
}
Then you can use it like this:
// run the function and see if its not in the array already
if (!codeInArray($arrays, $_GET['tourcode'], $_GET['promocode'])) {
// add the new entry to `$arrays`
$arrays[] = [
$_GET['tourcode'],
$_GET['promocode'],
];
}
As I understood changing your statement for !in_array might be the solution:
if (!in_array(array($_REQUEST['tourcode'],$_REQUEST['promocode']),$array))
<?php
$array = array(
0=>array(
0=>'VUM',
1=>'UA0885'
),
1=>array(
0=>'VUA',
1=>'UA0885'
)
);
$tour_code = trim($_REQUEST['tourcode']);
$promo_code = trim($_REQUEST['promocode']);
$filterarray = array();
$counter = 0;
foreach($array as $subarray){
foreach($subarray as $key => $value){
if(!in_array($tour_code , $subarray) || !in_array($promo_code , $subarray)){
$filterarray[$counter][] = $value;
}
}
$counter++;
}
print_r($filterarray);
?>
how can I add an extra dimesion before each element in N-dimensional array (recursively)? Let's say I have
Array
(
[room] => Array
(
[bed] = Array
(
[material] => wood
)
)
)
And I want to add an extra "[0]" dimension before room, bed and material. (Adding dimension only if the last element is an array). I also want to distinguish, if there already is the extra [0] dimension, so it will not appear twice .. + I don't want to add [0] if the array key is named "#attribute".
I'm trying to figure it out, but I'm really lost. This is what I've got so far..
function normalize_array (&$array) {
if (is_array($array)) {
if (!isset($array[0])) {
$array = array ( "0" => $array);
}
foreach ($array[0] as $next) {
normalize_array ($next);
}
}
}
but it does not work recursively. Any help will be appreciated. Thanks!
From the documentation of foreach:
In order to be able to directly modify array elements within the loop
precede $value with &. In that case the value will be assigned by reference.
So if you modify your function like this, it works:
function normalize_array (&$array) {
if (is_array($array)) {
if (!isset($array[0])) {
$array = array ( "0" => $array);
}
foreach ($array[0] as &$next) { // <-- add & here
normalize_array ($next);
}
}
}
Possible solution (tested just a little, but seems to work):
function normalize_array($array, $keys){
$new = array();
foreach($array as $key => $value){
if (in_array($key, $keys) && is_array($value)){
$new["0"] = array($key => normalize_array($value, $keys));
} else {
$new[$key] = $value ;
}
}
return $new ;
}
$data = array(
"room" => array(
"bed" => array(
"material" => "wood"
)
)
);
$keys = array("room", "bed", "material");
$new = normalize_array($data, $keys);
var_dump($new);
Final solution:
function normalize_array_rec (&$array) {
if (is_array($array)) {
if (!isset($array[0])) {
$array = array ( "0" => $array);
}
$i = 0;
while (isset($array[$i])) {
foreach ($array[$i] as &$next) {
normalize_array_rec ($next);
}
$i++;
}
}
}
Forgot to call function in each instance of array, not only in [0] index.
I have a function that accepts an array parameter as
array('employee_name' => 'employee_location' )
eg:
array('John' => 'U.S', 'Dave' => 'Australia', 'Unitech' => 'U.S' )
I wish to keep 'U.S' as the default location and a optional value, so
So If I pass
array('John', 'Dave' => 'Australia', 'Unitech')
Is there a in-build function in PHP that automatically converts it to
array('John' => 'U.S', 'Dave' => 'Australia', 'Unitech' => 'U.S' )
There is no built-in function for that.
You should loop through your array and check if the key is numeric. If it is, use the value as the key and add your default as the value.
Simple example (using a new array for clarity):
$result = array();
foreach ($arr as $key => $value)
{
if (is_int($key)) // changed is_numeric to is_int as that is more correct
{
$result[$value] = $default_value;
}
else
{
$result[$key] = $value;
}
}
Obviously this would break on duplicate names.
Note that MI6 will hunt you down: $agents = array('007' => 'UK'); will be transformed into $agents['UK'] => 'US'... I know UK and US have a "special relation", but this is taking things a tad far, IMHO.
$agents = array('007' => 'UK');
$result = array();
foreach($agents as $k => $v)
{
if (is_numeric($k))//leave this out, of course
{
echo $k.' won\'t like this';//echoes 007 won't like this
}//replace is_numeric with is_int or gettype($k) === 'integer'
if (is_int($k))
{//'007' isn't an int, so this won't happen
$result[$v] = $default;
continue;
}
$result[$k] = $v;
}
Result and input look exactly alike in this example.
foreach ($arr as $k => $v) {
if (is_int($k)) {
unset($arr[$k]);
$arr[$v] = 'U.S.';
}
}
I would work with something like this:
foreach ( $array AS $key => $value )
{
if ( is_numeric($key) )
{
$key = 'U.S';
}
$array[$key] = $value;
}
I am wondering if I could explain this.
I have a multidimensional array , I would like to get the count of particular value appearing in that array
Below I am showing the snippet of array . I am just checking with the profile_type .
So I am trying to display the count of profile_type in the array
EDIT
Sorry I've forgot mention something, not something its the main thing , I need the count of profile_type==p
Array
(
[0] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => p
[birthyear] => 1978
[is_elite] => 0
)
)
[1] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => d
[birthyear] => 1972
[is_elite] => 1
)
)
)
Easy solution with RecursiveArrayIterator, so you don't have to care about the dimensions:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$counter = 0
foreach ($iterator as $key => $value) {
if ($key == 'profile_type' && $value == 'p') {
$counter++;
}
}
echo $counter;
Something like this might work...
$counts = array();
foreach ($array as $key=>$val) {
foreach ($innerArray as $driver=>$arr) {
$counts[] = $arr['profile_type'];
}
}
$solution = array_count_values($counts);
I'd do something like:
$profile = array();
foreach($array as $elem) {
if (isset($elem['Driver']['profile_type'])) {
$profile[$elem['Driver']['profile_type']]++;
} else {
$profile[$elem['Driver']['profile_type']] = 1;
}
}
print_r($profile);
You may also use array_walk($array,"test") and define a function "test" that checks each item of the array for 'type' and calls recursively array_walk($arrayElement,"test") for items of type 'array' , else checks for the condition. If condition satisfies, increment a count.
Hi You can get count of profuke_type==p from a multi dimensiona array
$arr = array();
$arr[0]['Driver']['id'] = 4;
$arr[0]['Driver']['profile_type'] = 'p';
$arr[0]['Driver']['birthyear'] = 1978;
$arr[0]['Driver']['is_elite'] = 0;
$arr[1]['Driver']['id'] = 4;
$arr[1]['Driver']['profile_type'] = 'd';
$arr[1]['Driver']['birthyear'] = 1972;
$arr[1]['Driver']['is_elite'] = 1;
$arr[2]['profile_type'] = 'p';
$result = 0;
get_count($arr, 'profile_type', 'd' , $result);
echo $result;
function get_count($array, $key, $value , &$result){
if(!is_array($array)){
return;
}
if($array[$key] == $value){
$result++;
}
foreach($array AS $arr){
get_count($arr, $key, $value , $result);
}
}
try this..
thanks
I have a result set as an array from a database that looks like:
array (
0 => array (
"a" => "something"
"b" => "something"
"c" => "something"
)
1 => array (
"a" => "something"
"b" => "something"
"c" => "something"
)
2 => array (
"a" => "something"
"b" => "something"
"c" => "something"
)
)
How would I apply a function to replace the values of an array only on the array key with b? Normally I would just rebuild a new array with a foreach loop and apply the function if the array key is b, but I'm not sure if it's the best way. I've tried taking a look at many array functions and it seemed like array_walk_recursive is something I might use, but I didn't have luck in getting it to do what I want. If I'm not describing it well enough, basically I want to be able to do as the code below does:
$arr = array();
foreach ($result as $key => $value)
{
foreach ($value as $key2 => $value2)
{
$arr[$key][$key2] = ($key2 == 'b' ? $this->_my_method($value2) : $value2);
}
}
Should I stick with that, or is there a better way?
Using array_walk_recursive:
If you have PHP >= 5.3.0 (for anonymous functions):
array_walk_recursive($result, function (&$item, $key) {
if ($key == 'b') {
$item = 'the key is b!';
}
});
Otherwise something like:
function _my_method(&$item, $key) {
if ($key == 'b') {
$item = 'the key is b!';
}
}
array_walk_recursive($result, '_my_method');
Untested but I think this will work.
function replace_b (&$arr)
{
foreach ($arr as $k => $v)
{
if ($k == 'b')
{
/* Do something */
}
if (is_array($v)
{
replace_b($arr[$k]);
}
}
}
The function will move through an array checking the keys for b. If the key points to an array it recursively follows it down.
use array_walk_recursive documented here
$replacer = function($x) {return "I used to be called $x";}; //put what you need here
$replaceB = function(&$v, $k) use ($replacer) {if ($k === 'b') $v = $replacer($v);};
array_walk_recursive($arr, $replaceB);
The replacer function might be overkill. You can replace it with a literal or anything you like.