php check array value for duplicate [duplicate] - php

This question already has answers here:
How to detect duplicate values in PHP array?
(13 answers)
Closed 9 years ago.
i have this below array:
PHP
$arr=array('A','A','B','C');
i want to check value and if values are duplicate must be alert error
PHP
$chk=array_count_values($array);
if ( $chk[0] < 1 || $chk[2] < 1 || $chk[3] < 1 || $chk[4] < 1 )
echo 'array must be uniq';

Using array_unique(), this can be easily refactored into a new function:
function array_is_unique($array) {
return array_unique($array) == $array;
}
Example:
$array = array("a", "a", "b", "c");
echo array_is_unique($array) ? "unique" : "non-unique"; //"non-unique"

Try this :
$arr = array('A','A','B','C');
if(count($arr) != count(array_unique($arr))){
echo "array must be uniq";
}

Just try with:
if ( count($arr) != count(array_unique($arr)) ) {
echo 'array must be uniq';
}

You could walk thhrough it with a foreach loop and then use the strpos function to see if a string contains duplicates

From Php documentation
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.

Related

Array_Search For Multiple Same Elements [duplicate]

This question already has answers here:
How to search Array for multiple values in PHP?
(6 answers)
Closed 2 years ago.
there is an array like $arr = array(1,2,3,3,3,4,5) . What if we want to get all indexes that have values 3?
i used array_search(3, $arr) but it just give back an integer and just the first index that has value '3'
how can we get an array like $indexes = array(2,3,4) that shows all indexes that have value 3?
your help will be highly appreciated
You can use array_keys with search value PHP Doc
Demo
array_keys($arr,3)
array_keys() returns the keys, numeric and string, from the array.
If a search_value is specified, then only the keys for that value are
returned. Otherwise, all the keys from the array are returned.
you can use array_keys:
foreach (array_keys($arr) as $key) if ($arr[$key] == 3) $result[] = $key;
With that solution you can create complex filters. In this case we compare every value to be the number three (=== operator). The filter returns the index, when the comparision true, else it will be dropped.
$a = [1,2,3,4,3,3,5,6];
$threes = array_filter($a, function($v, $k) {
return $v === 3 ? $k : false; },
ARRAY_FILTER_USE_BOTH
);
$threes Is an array containing all keys having the value 3.
array(3) { 2, 4, 5 }

Can't access to array once I sorted it [duplicate]

This question already has answers here:
Sort array not working
(2 answers)
Closed 10 months ago.
I am trying to sort an array. When I print the sort results to screen it prints 1. Why does it print 1 instead of the contents of the sorted array?
Here is my code:
session_start();
if (isset($_POST))
{
$_SESSION['total_elements'];
$value1 = $_POST["username"];
if (isset($_SESSION['total_elements']))
{
if (!empty($value1))
{
array_push($_SESSION['total_elements'], $value1);
}
}
}
$a = array();
$a = $_SESSION['total_elements'];
print_r($asceding_order) = sort($a); // printing 1
sort just sorts the array, doesn't return it :) It is returning boolean TRUE to you which your echo is showing as 1
echo $asceding_order= sort($a); // wrong
Right way would be
sort($a);
print_r($a);
Here is the function prototype for reference
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
#Fernando - instead of using:
print_r($asceding_order) = sort($a);
or assigning value, just do:
$a = $_SESSION['total_elements'];
sort($a);
This will sort the array and return it.

php array skip values greater than X [duplicate]

This question already has answers here:
How to filter an array by a condition
(9 answers)
Closed 6 years ago.
I have an array with values between 1-100. However, in case of an error, is there a way to make one final check just to be sure I skip/ignore values greater than 100 and the output is between 1-100?
This is where array_filter() comes in handy.
$lower_limit = 1;
$upper_limit = 100;
$array = array_filter(
$array,
function ($value) use ($lower_limit, $upper_limit) {
return ($value >= $lower_limit && $value <= $upper_limit);
}
);
Using array_filter is a way to it.
It will iterate through your array and filters it using the supplied function. In the end you'll get an array with only elements between 1 and 100.
$arr = array(
1, 2, 99, 201,
);
$goodArr = array_filter($arr, function($value){
return ($value >= 1 && $value <= 100);
});

Update array value in foreach loop [duplicate]

This question already has answers here:
How to modify an array's values by a foreach loop?
(2 answers)
Closed 4 months ago.
I have this piece of code :
$start = ['23','', 'what'];
foreach($start as $i){
if($i ==''){
$i = 'satisfaction';
}
}
print_r($start);
The output is :
Array
(
[0] => 23
[1] =>
[2] => what
)
Why did index [1] not get replaced with 'satisfaction'. In other words : I don't want to create a new array, but change the index of an existing array. Actually, what I'm trying to achieve is to do intval() on those indexes that are not empty (since intval on an empty index returns 0, which is not what I want).
According to the manual:
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 in your case, you should add &:
$start = ['23','', 'what'];
foreach($start as &$i){
// ^ reference
if($i === ''){
$i = 'satisfaction';
}
}
Sidenote: If your intent is to change those numeric values into data type integer, you can use (as you stated) intval or a simple type cast.
$start = ['23','', 'what'];
foreach($start as &$i){
if(is_numeric($i)){
$i = (int) $i;
}
}
var_dump($start);
Because foreach(...) acts "a bit" as a read-only iterator. If you want to modify elements, you'll have to access by reference.
example :
foreach ($start as &$i) {
}
For more info, see doc : http://php.net/manual/fr/control-structures.foreach.php
In your example you are just setting the variable $i, which is just a temporary variable for the loop. Instead, keep the array key in the loop and use that to set the value in the array:
$start = ['23','', 'what'];
foreach($start as $k=>$i){
if($i ==''){
$start[$k] = 'satisfaction';
}
}

Search array and return multiple matches [duplicate]

This question already has answers here:
How to search Array for multiple values in PHP?
(6 answers)
Closed 8 years ago.
For example if I am searching for a key with a value 5 in my array $cake, I could use the following code:
$cake = array("a"=>6,"b"=>5,"c"=>6);
echo array_search(5, $cake, true); // returns "b";
But if my $cake array contains multiple matches, only the first match is returned:
$cake = array("a"=>6,"b"=>5,"c"=>5,"d"=>5,"e"=>5);
echo array_search(5, $cake, true); // returns "b";
How can I return multiple matches as an array? Like this:
$cake = array("a"=>6,"b"=>5,"c"=>5,"d"=>5,"e"=>5);
// return array("b","c","d","e");
As noted in the docs:
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.
print_r(array_keys($cake, 5, true));
You can use array_intersect.
array_intersect — Computes the intersection of arrays
$matches = array_keys(array_intersect($cake, array(5)));
print_r($matches);
Outputs
Array
(
[0] => b
[1] => c
[2] => d
[3] => e
)
you can do this:
for($index = 0; $index <= count($cake); $index++){
if(!array_search(5, $cake[$index], true) == false){
echo array_search(5, $cake[$index], true);
}
}

Categories