I have an array that looks like this...
Array
(
[0] => red
[1] => red
[2] => red
)
I am trying to check if red is the only thing in the array, I would want it to fail if the array looked like this...
Array
(
[0] => red
[1] => yellow
[2] => red
)
Using array_unique() you can just count the number of occurances returned. If its > 1 you have not got all red
<?php
$array = ['red','red','red'];
if ( count(array_unique($array)) == 1 && array_unique($array)[0] == 'red' ) {
echo 'all red';
} else {
echo 'error';
}
Use combination of count() and array_filter() to find count of unwanted item in array.
$invalidItems = count(array_filter($arr, function($item){
return $item != 'red';
}));
if ($invalidItems)
echo 'invalid';
else
echo 'valid';
Check result in demo
You could just use array_unique() to get it to remove duplicates and then count the size of the remaining list, you can also then check that the 1 value is whatever value your expecting...
$unique = array_unique($a);
if ( count($unique) == 1 && $unique[0] == 'value' ) {
}
You can do it like this:
$array = [
'foo',
'foo',
'foo'
];
$values = array_count_values($array);
$count = count($array);
if (!empty($values['foo']) && $count === $values['foo']) {
echo 'all array values match foo';
} else {
echo 'foo not found in array';
}
here we count values in the array vs the overall count of the array
Edit: The only problem is, you have to know the value you're comparing against to get the result
Edit 2: Addressing issue raised by MickMackusa:
and the other problem is, if the value that you are looking for doesn't exist at all in the input array, then it won't exist as a key in the $values array and thus your code will generate a Notice. ...not good.
You don't need more than one function call to check for non-red values exist. The following checks if there are any non-red elements.
Codes (Demo)
$array = ['red','red','red'];
var_export(!array_diff($array, ['red'])); // true
echo "\n";
var_export(!array_filter($array, function($v){return $v !== 'red';})); // true
$array = ['red','yellow','red'];
var_export(!array_diff($array, ['red'])); // false
echo "\n";
var_export(!array_filter($array, function($v){return $v !== 'red';})); // false
I think array_filter() is a more "direct" technique, but array_diff() doesn't need a custom function so it is arguably easier to read.
If your coding logic must require the existence of red as well as disqualify arrays that contain a non-red element, then just add a condition that checks if the array has any elements. (more precise demo)
And for best performance, use a loop with a break -- this way you don't have to iterate the entire array unless absolutely necessary. Early breaks are a good thing. Demo
$array = ['red','yellow','red'];
$result = true;
foreach ($array as $value) {
if ($value != 'red') {
$result = false;
break;
}
}
Check if red is there, then remove duplicate values and check that there is only one:
if(in_array('red', $array) && (count(array_unique($array)) == 1)) {
// yes
}
Old school foreach (all) red or dead:
<?php
$things = ['red', 'white', 'blue'];
foreach($things as $colour)
if ($colour !== 'red')
throw new Exception('dead');
Related
I have an array as such:
$array = ["1","0","0","1","1"]
//replace with
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
// only if the original array had a value of "1".
// for example this is my final desired output:
$newArray = ["honda","0","0","bmw","chevy"]
I want to change each value in a specific order IF and only if the array value is equal to "1".
For example the values, "honda", "toyota", "mercedes", "bmw", "chevy" should only replace the array values if the value is "1" otherwise do not replace it and they must be in the right position for example the first element in the array must only be changed to honda, not toyota or any of the other values.
I know I must iterate through the array and provide an if statement as such:
foreach($array as $val) {
if($val == 1){
//do something
} else {
return null;
}
}
Please guide me in the right direction and describe how to replace the values in order, so that toyota cannot replace the first array value only the second position.
You can so something like this - iterating over the array by reference and replacing when the value is 1 (string) and the value in the replace array exists:
foreach($array as $key => &$current) {
if($current === '1' && isset($replace[$key]))
$current = $replace[$key];
}
Output:
Array
(
[0] => honda
[1] => 0
[2] => 0
[3] => bmw
[4] => chevy
)
As per your comment, to output an imploded list of the cars that do have values, you can do something like this - filtering out all zero values and imploding with commas:
echo implode(
// delimiter
', ',
// callback - filter out anything that is "0"
array_filter($array, function($a) {
return $a != '0';
})
);
Currently, our if is asking if $val is true (or if it exists) while your numeric array's values are strings.
Try this:
$array = ["1","0","0","1","1"]
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
foreach($array as $key => $val) {
if($val === '1'){ // if you only want honda
$array[$key] = $newArray[$key];
} else {
return null;
}
}
PHP Code
$array = array("1","0","0","1","1");
$newArray = array("honda","toyota","mercedes","bmw","chevy");
foreach($array as $key => $val) {
if($val === '1')
$array[$key] = $newArray[$key];
}
Would produce the answer you're looking for
I have inserted some elements (fruit names) queried from mySQL into an array. Now, I would like to remove certain items from the array. I want to remove 'Apple' and 'Orange' if the exist from the array. This is what I tried but I am getting an error message.
Array Example:
Array ( [1] => Orange [2] => Apple)
foreach($terms as $k => $v)
{
if (key($v) == "Apple")
{
unset($terms[$k]);
}
elseif( key($v) == "Orange")
{
unset($terms[$k]);
}
}
>>> Warning: key() expects parameter 1 to be array, string given //same error repeated 4 times
I referred to this link here: How do you remove an array element in a foreach loop?
I would be grateful if anyone can point out what I did wrong.
Have you tried it this way:
foreach($terms as $k => $v)
{
if ($v == "Apple")
{
unset($terms[$k]);
}
elseif($v == "Orange")
{
unset($terms[$k]);
}
}
Explanation:
The $fr is your actual array of all fruits.. and your $rm is another array that contains list of items to be removed from your $fr array.
Using a foreach cycle through the $rm array and see if the element exists on the $fr array , if found, unset() it.
The code...
<?php
$fr = array('Apple','Orange','Pineapple'); //<-- Your actual array
$rm = array('Apple','Orange'); //<--- Elements to be removed
foreach($rm as $v)
{
if(in_array($v,$fr))
{
unset($fr[array_search($v,$fr)]);
}
}
print_r($fr);
OUTPUT :
Array
(
[2] => Pineapple
)
Using array_diff()
print_r(array_diff($fr,$rm));
Code Demonstration
Let's say I have a multidimensional array like this:
[
["Thing1", "OtherThing1"],
["Thing1", "OtherThing2"],
["Thing2", "OtherThing3"]
]
How would I be able to count how many times the value "Thing1" occurs in the multidimensional array?
you can use array_search for more information see this http://www.php.net/manual/en/function.array-search.php
this code is sample of this that is in php document sample
<?php
function recursiveArraySearchAll($haystack, $needle, $index = null)
{
$aIt = new RecursiveArrayIterator($haystack);
$it = new RecursiveIteratorIterator($aIt);
$resultkeys;
while($it->valid()) {
if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND (strpos($it->current(), $needle)!==false)) { //$it->current() == $needle
$resultkeys[]=$aIt->key(); //return $aIt->key();
}
$it->next();
}
return $resultkeys; // return all finding in an array
} ;
?>
If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
http://www.php.net/manual/en/function.array-keys.php
Try this :
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
echo "<pre>";
$res = array_count_values(call_user_func_array('array_merge', $arr));
echo $res['Thing1'];
Output :
Array
(
[Thing1] => 2
[OtherThing1] => 1
[OtherThing2] => 1
[Thing2] => 1
[OtherThing3] => 1
)
It gives the occurrence of each value. ie : Thing1 occurs 2 times.
EDIT : As per OP's comment : "Which array do you mean resulting array?" - The input array. So for example this would be the input array: array(array(1,1),array(2,1),array(3,2)) , I only want it to count the first values (1,2,3) not the second values (1,1,2) – gdscei 7 mins ago
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
$res = array_count_values(array_map(function($a){return $a[0];}, $arr));
echo $res['Thing1'];
function showCount($arr, $needle, $count=0)
{
// Check if $arr is array. Thx to Waygood
if(!is_array($arr)) return false;
foreach($arr as $k=>$v)
{
// if item is array do recursion
if(is_array($v))
{
$count = showCount($v, $needle, $count);
}
elseif($v == $needle){
$count++;
}
}
return $count;
}
Using in_array can help:
$cont = 0;
//for each array inside the multidimensional one
foreach($multidimensional as $m){
if(in_array('Thing1', $m)){
$cont++;
}
}
echo $cont;
For more info: http://php.net/manual/en/function.in-array.php
try this
$arr =array(
array("Thing1","OtherThing1"),
array("Thing1","OtherThing2"),
array("Thing2","OtherThing3")
);
$abc=array_count_values(call_user_func_array('array_merge', $arr));
echo $abc[Thing1];
$count = 0;
foreach($array as $key => $value)
{
if(in_array("Thing1", $value)) $count++;
}
If you prefer code brevity zero global scope pollution, you can count every value and access the one count that you do want:
echo array_count_values(array_merge(...$array))['Thing1'] ?? 0;
If you don't want to bother counting values where the count will never be needed, then you can visit leafnodes with array_walk_recursive() and +1 everytime the target value is encountered.
$thing1Count = 0;
array_walk_recursive($array, function($v) use(&$thing1Count) { $thing1Count += ($v === 'Thing1'); });
echo $thing1Count;
Both snippets return 2. Here's a Demo.
I want to replace all array values with 0 except work and home.
Input:
$array = ['work', 'homework', 'home', 'sky', 'door']
My coding attempt:
$a = str_replace("work", "0", $array);
Expected output:
['work', 0, 'home', 0, 0]
Also my input data is coming from a user submission and the amount of array elements may be very large.
A bit more elegant and shorter solution.
$aArray = array('work','home','sky','door');
foreach($aArray as &$sValue)
{
if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}
The & operator is a pointer to the particular original string in the array. (instead of a copy of that string)
You can that way assign a new value to the string in the array. The only thing you may not do is anything that may disturb the order in the array, like unset() or key manipulation.
The resulting array of the example above will be
$aArray = array('work','home', 0, 0)
A loop will perform a series of actions many times. So, for each element in your array, you would check if it is equal to the one you want to change and if it is, change it. Also be sure to put quote marks around your strings
//Setup the array of string
$asting = array('work','home','sky','door')
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work' || $asting[$i] == 'home')
$asting[$i] = 0;
}
Here is some suggested reading:
http://www.php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/language.control-structures.php
But if you are struggling on stuff such as looping, you may want to read some introductory programming material. Which should help you really understand what's going on.
A bit other and much quicker way, but true, need a loop:
//Setup the array of string
$asting = array('bar', 'market', 'work', 'home', 'sky', 'door');
//Setup the array of replacings
$replace = array('home', 'work');
//Loop them through str_replace() replacing with 0 or any other value...
foreach ($replace as $val) $asting = str_replace($val, 0, $asting);
//See what results brings:
print_r ($asting);
Will output:
Array
(
[0] => bar
[1] => market
[2] => 0
[3] => 0
[4] => sky
[5] => door
)
An alternative using array_map:
$original = array('work','home','sky','door');
$mapped = array_map(function($i){
$exclude = array('work','home');
return in_array($i, $exclude) ? 0 : $i;
}, $original);
you may try array_walk function:
function zeros(&$value)
{
if ($value != 'home' && $value != 'work'){$value = 0;}
}
$asting = array('work','home','sky','door','march');
array_walk($asting, 'zeros');
print_r($asting);
You can also give array as a parameter 1 and 2 on str_replace...
Just a small point to the for loop. Many dont realize the second comparing task is done every new iteration. So if it was a case of big array or calculation you could optimize loop a bit by doing:
for ($i = 0, $c = count($asting); $i < $c; $i++) {...}
You may also want to see http://php.net/manual/en/function.array-replace.php for original problem unless the code really is final :)
Try This
$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
$key = array_search($val, $your_array);
$your_array[$key] = 0;
}
print_r($your_array);
There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise. For best maintainability, I recommend separating your list of targeted string as a lookup array. By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.
Code: (Demo)
$array = ['work', 'homework', 'home', 'sky', 'door'];
$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);
foreach ($array as &$v) {
$v = $lookup[$v] ?? 0;
}
var_export($array);
Output:
array (
0 => 'work',
1 => 0,
2 => 'home',
3 => 0,
4 => 0,
)
You can very easily, cleanly extend your list of targeted strings by merely extending $keep.
If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)
var_export(
array_map(fn($v) => $lookup[$v] ?? 0, $array)
);
this my final code
//Setup the array of string
$asting = array('work','home','sky','door','march');
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
$asting[$i] = 20;
} elseif($asting[$i] == 'home'){
$asting[$i] = 30;
}else{
$asting[$i] = 0;
}
echo $asting[$i]."<br><br>";
$total += $asting[$i];
}
echo $total;
I have an array like
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
)
How can I get a key by providing a value?
e.g. if i search for "buffaloes" array_search may return "2".
Thanks
$myArray =array
(
"0"=>array("dogs",98),
"1"=>array("cats",56),
"2"=>array("buffaloes",78)
);
function findInArray($term, $array) {
foreach($array as $key => $val) {
if(in_array($term, $val, true)) {
return $key;
}
}
}
echo findInArray('buffaloes', $myArray); // 2
echo findInArray(78, $myArray); // 2
function asearch($key, $myArray) {
for ($i = 0; $i < sizeof($myArray); $i++) {
if ($myArray[$i][0] == $key) {
return $i;
}
}
return -1; # no match
}
Though, you'd probably want to restructure your array to:
$myarray = array(
'dogs' => 98,
'cats' => 56,
'buffaloes' => 78
);
And just do:
$myArray['buffaloes']; # 78
The only way you can do it is to iterate over every item and preform a Linear Search
$i = -1;
foreach ($myArray as $key => $item){
if ( $item[0] == 'buffaloes' ){
$i = $key;
break;
}
}
//$i now holds the key, or -1 if it doesn't exist
As you can see, it is really really inefficient, as if your array has 20,000 items and 'buffaloes' is the last item, you have to make 20,000 comparisons.
In other words, you need to redesign your data structures so that you can look something up using the key, for example a better way may be to rearrange your array so that you have the string you are searching for as the key, for example:
$myArray['buffaloes'] = 76;
Which is much much faster, as it uses a better data structure so that it only has to at most n log n comparisons (where n is the number of items in the array). This is because an array is in fact an ordered map.
Another option, if you know the exact value of the value you are searching for is to use array_search
I never heard of built in function. If you want something more general then above solutions you shold write your own function and use recursion. maybe array_walk_recursive would be helpful
You can loop over each elements of the array, testing if the first element of each entry is equal to "buffaloes".
For instance :
foreach ($myArray as $key => $value) {
if ($value[0] == "buffaloes") {
echo "The key is : $key";
}
}
Will get you :
The key is : 2
Another idea (more funny ?), if you want to whole entry, might be to work with array_filter and a callback function that returns true for the "bufalloes" entry :
function my_func($val) {
return $val[0] == "buffaloes";
}
$element = array_filter($myArray, 'my_func');
var_dump($element);
Will get you :
array
2 =>
array
0 => string 'buffaloes' (length=9)
1 => int 78
And
var_dump(key($element));
Gves you the 2 you wanted.