PHP Associative Array count & extract - php

I've got the following array
$array = [
1 => 'test',
2 => 'test',
3 => 'test',
4 => 'another'
];
What i want to obtain from this is:
The count of value 'test' $values (It's variable);
After that i will need to get all keys for value 'test' do to the next assumption:
if (\count($values) > 1) {
// do something with keys of value 'test'
echo $keysOfThatValue;
}
I will need to do the upper assumption to all of the array elements grouped by array value.

You can use array_keys with a search argument, then just count those:
$count = count($keys = array_keys($array, 'test'));
Or following your code. The if only executes if test is found and keys are returned:
if($keys = array_keys($array, 'test')) {
// do something with $keys of value 'test'
}

array_filter() can be used to get an array of only entries with the value "test".

Related

How do I echo the key or value from inside a multidimentional array without writing its key in the echo statement?

I have a multidimensional array and would like to call the key and the value separately, of individual levels inside the array.
Now with a normal array, I can do this by writing:
$example = array('one', 'two', 'three');
echo $example[0];
and this will return: one
However, when I try to do this with a multidimensional array like so:
$example = array(
'optionone' => array('one', 'two', 'three'),
'optiontwo' => array('a','b','c'),
'optionthree' => array(1,2,3)
);
echo $example[0];
echo $example[0][0];
Instead of echoing 'optionone' followed by 'one' I get nothing returned, and no error code.
When trying to see why this is happening by using:
var_dump($example[0)];
or
var_dump($example[0][0]);
NULL is returned.
I would really appreciate if someone could tell me how to correctly get/echo/call 'optionone' to return from the array as a string: 'optionone' without writing the name and how can I call the value 'one' without writing:
$example['optionone'][0];
I'm trying to create something where it doesn't know the key name, so it rather is going by the position of the keys but i would like to be able to return the key names at different points in the program but I can't seem to figure out how to do this.
This should work for you:
Just get your associative keys into an array with array_keys(), so you can access them as a 0-based indexed array, e.g.
So with array_keys($example) you end up with the following array:
Array
(
[0] => optionone
[1] => optiontwo
[2] => optionthree
)
Which you then can access as you want it:
<?php
$example = array(
'optionone' => array('one', 'two', 'three'),
'optiontwo' => array('a','b','c'),
'optionthree' => array(1,2,3)
);
$keys = array_keys($example);
echo $keys[0] . "<br>";
echo $example[$keys[0]][0];
?>
output:
optionone
one
The outer array in your example is an associative array. There is not value at index 0. If you need to get to to the first key in the associative array without knowing the name of the key you would need to do something like:
$example = array(
'optionone' => array('one', 'two', 'three'),
'optiontwo' => array('a','b','c'),
'optionthree' => array(1,2,3)
);
//get array keys into array
$example_keys = array_keys($example);
// get value at first key in $example array
$first_inner_array = $example[$example_keys[0]];
// get first value from first inner array
$first_value = $first_inner_array[0];
// Or to get an arbitrary value:
$x = ... // whatever inner array you want to get into
$y = ... // whatever index within inner array you want to get to
$value = $example[$example+keys[$x]][$y];
I would say that if you find yourself doing this in code, you probably have your data structured poorly. Associative arrays are not meant to convey any sort of element ordering. For example, if you changed your example array to this:
$example = array(
'optiontwo' => array('a','b','c'),
'optionone' => array('one', 'two', 'three'),
'optionthree' => array(1,2,3)
);
You would get a different value retrieved from above code even though the relationship between outer array keys and inner array contents has not been changed.
not tested
foreach($example as $f_array){
foreach($f_array as $key => $val){ //iterate over each array inside first array
echo $key; //should print 'optionone'
echo $val[0]; //should print 'one'
break;
}
}

PHP getting values of the objects by key inside array

Hi all I have an array "$decodedData" of object from json data.
var_export($decodedData);
returns next:
array ( 0 => array ( 'number' => '2', 'type' => 'accs', ), 1 => array ( 'number' => '5', 'type' => 'accs', ), )
I'm trying to output all the "numbers" values:
foreach ($decodedData as $number)
{
echo implode(',', $number);
}
but I'm getting "type" values either
2,accs5,accs
How can I get rid of those?
You can use array_map to accomplish that.
The first parameter is a callback function that will receive each element and return something to replace it with. In this case, we are returning the number key of each element.
$result = array_map(function($val) {
return $val['number'];
}, $array);
echo implode(',', $result);
You're looping through an array of arrays, so $number is returning a complete array, not the number value. To access the number value of each, do something like this:
foreach ($decodedData as $number=>$val){
echo implode(',', $val['number']);
}

echo value from multidimensional array

My PHP call is storing a table from mySQL with the following code.
while (mysqli_stmt_fetch($stmtMyCountTotals)) {
$stmtMyCountTotalsrow = array(
'IndividualUnitsCounted' => $IndividualUnitsCounted,
'IndividualUnitsAdjusted' => $IndividualUnitsAdjusted
);
$stmtMyCountTotalsrows[] = $stmtMyCountTotalsrow;
}
$stmtMyCountTotals->close();
I can not seem to pull a individual value from it. For Example If I want to pull a number from column 1 row 2. I know this is a basic question but I can not seem to find an answer.
This is a multidimensional array, so you would access it like so:
$row1col2 = $stmtMyCountTotalsrows[1][2]
$row2col1 = $stmtMyCountTotalsrows[2][1]
But since it is associative you would want:
$var = $stmtMyCountTotalsrows[1]['IndividualUnitsCounted'];
If you want to access it by column, then you would need to retrieve the column names first into an array:
$cols = array_keys($stmtMyCountTotalsrows[0]);
$var = $stmtMyCountTotalsrows[1][$cols[1]]
// ^ where this is the column number
There are no column numbers in your array, the second dimension is an associative array. So it should be:
$stmtMyCountTotalsrows[$row_number]['IndividualUnitsCounted']
$stmtMyCountTotalsrows[$row_number]['IndividualUnitsAdjusted']
You have an array inside another array. Or a multidimensional array. It looks like this:
Array(
0 => Array(
'IndividualUnitsCounted' => 'Something',
'IndividualUnitsAdjusted' => 'Something Else'
),
1 => Array(
'IndividualUnitsCounted' => 'Yet another something',
'IndividualUnitsAdjusted' => 'Final something'
),
...
...
)
If this array is called $stmtMyCountTotalsrows:
$stmtMyCountTotalsrows[0]['IndividualUnitsCounted'] returns "Something"
$stmtMyCountTotalsrows[0]['IndividualUnitsCounted'] returns "Something Else"
$stmtMyCountTotalsrows[1]['IndividualUnitsAdjusted'] returns "Yet another something"
$stmtMyCountTotalsrows[1]['IndividualUnitsAdjusted'] returns "Final something"
If you don't know the name of the columns beforehand, you could use current() for the first:
echo current($stmtMyCountTotalsrows[1]);
Alternatively, use array_slice():
echo current(array_slice(stmtMyCountTotalsrows, 0, 1));

How to find the indices of duplicate values in an array

I have two arrays, array1 and array2 that I am using to populate a table, so that array1[5] and array2[5] both fill the same row but I want to write a function that removes both array1[i] and array2[i] if array1[i] is a duplicate of array1[j] for some j less than i, where i is an arbitrary positive integer.
To accomplish this I was to work out the indices of duplicate values in array1 and then use this information to delete the entries from both array1 and array2 for these indices, before populating my table.
Any ideas gratefully received.
Thanks.
The array_unique function removes dupes, but preserves keys. Then you can just iterate through the other array and remove the keys that don't exist in the first one.
$array1 = array_unique($array1);
foreach ($array2 as $key => $val) {
if (!array_key_exists($key,$array1)) unset($array2[$key]);
}
$array1_keys = array_keys($array1); // all keys
$unique = array_keys(array_unique($array1)); // keys of unique values
$duplicate = array_diff($array1_keys, $unique_keys); // keys of the duplicate values
foreach($duplicate as $key){
unset($array2[$key]);
}
Sidenote: Be aware that array_diff uses string casting for comparison. If your array contains non scalar values you should have a look at array_udiff.
Edit: Mingos post in my eyes did not fully suit the question, looks like i was wrong :D
If your array keys are meaningful and not just a 0-based index and you want to keep the duplicate entry with the lowest key (as you indicate might be the case from your question) then you need to sort the array first. If you don't, you will get the first entry in the array for each duplicate value and not entry with the lowest key. Compare
$array = array( 5 => 'foo', 1 => 'bar', 2 => 'foo', 3 => 'bar' );
$array = array_unique( $array );
var_dump( $array );
with
$array = array( 5 => 'foo', 1 => 'bar', 2 => 'foo', 3 => 'bar' );
ksort( $array );
$array = array_unique( $array );
var_dump( $array );
In asociative arrays, you can get easily a counter of item to detect repeated and the first ocurrence with something as simple as (in this case using an associative array, where $array_key is the key to count) using array_count_values:
$index = null;
$array_by_columns = array_count_values(array_column($associative_array, $array_key);
foreach($array_by_columns) as $key => $ocurrences){
if($ocurrences > 1){
$index = $key;
}
}
If you have $index there are repeated element and also is the index of in the array.
A more compacted way in a line:
$index = null;
foreach(array_count_values(array_column($associative_array, $array_key)) as $key => $ocurrences)if($ocurrences > 1) $index = $key;
Data example:
[ARRAY] (start)
n0
KEY = 0
VALUE = {"user":"1","points":"10"}
n1
KEY = 1
VALUE = {"user":"4","points":"10"}
n2
KEY = 2
VALUE = {"user":"5","points":"30"}
n3
KEY = 3
VALUE = {"user":"1","points":"40"}
[ARRAY] (end)
More info:
array_count_values
array_column

How can I replace a specific key's value in an array in php?

I have a an array that has 3 values. After the user pushes the submit button I want it to replace the the value of a key that I specify with another value.
If I have an array with the values (0 => A, 1 => B, 2 => C), and the function is run, the resulting array should be (0 => A, 1 => X, 2 => C), if for example the parameter for the function tells it to the replace the 2nd spot in the array with a new value.
How can I replace a specific key's value in an array in php?
If you know the key, you can do:
$array[$key] = $newVal;
If you don't, you can do:
$pos = array_search($valToReplace, $array);
if ($pos !== FALSE)
{
$array[$pos] = $newVal;
}
Note that if $valToReplace is found in $array more than once, the first matching key is returned. More about array_search.
In case you want to have an inline solution you can use array_replace or array_replay_recrusive depending on which suits you best.
$replaced_arr = array_replace([
'key' => 'old_value',
0 => 'another_untouched_value'
],[
'key' => 'new_value'
]);
It would be best if your array is key/value pair

Categories