Array_search query in array - php

I could not get array key .
For example : i created array with information
[0] => Andrey:Makarov:525359:east::57.9318:33.2573:31591:424:1 [1] => John:Smith:752351:east::56.7318:23.6373:37491:424:1 and etc.
How i can find key of array if i know only identifier of person - 525359 ?
i have tried this code
$key = array_search('525359',$array);
echo 'key is',$key;
but it not works .
Maybe i need try create pattern attribute like in HTML ?

here is an example to get key based on regular expression , like it return the key of element who matches with ee inside a value .
$colors = array("red", "green", "blue", "yellow");
$key=0;
foreach ($colors as $value) {
if (preg_match("*ee*", $value)) {
echo $value." has key = ".$key."<br>";
break;
} else {
$key++;
}
}
output of this code is
green has key = 1

array_search only returns array entries with exact matches in the values.
The best option would be to re-key your array based on the identifier you wanted to match against, allowing you to filter more easily.
The second best option might be to use preg_grep which can search for a regular expression through the array entries. See https://secure.php.net/manual/en/function.preg-grep.php

Related

Regular expression to get the value from array

I need to get the value for a certain key, they key is not the same all the time.
initial part remains same but every time I get new id added in the end.
My array is like this:
senario 1:
Array
(
[custom_194_1] => 123
[_f_upload] => Save
)
senario 2:
Array
(
[custom_194_2] => 456
[_f_upload] => Save
)
I need to get the value 123 in senario 1, 456 in senario 2.
Can anyone please help me on how to get the value from this array key.
If your key is always the first element, and the array is $array the fastest way is:
$result = reset($array);
Or if you don't want to mess with the array's internal pointer:
$result = array_values($array)[0];
If you want the value of the key:
$key = array_keys($array)[0];
Thanks for your time guys. I'm using foreach to loop through and then checking with every key with substring. Hope it helps someone in future, not the very best solution though.
foreach($fields as $key => $val)
{
if(substr($key,0,10)=='custom_194'){
$realValue = $val;
echo "<br>value i'm looking for:";print_r($val);
}
}
Because you stated that you want the number at the end of the key and because you appear to want to learn more about regular expressions... This is not a hard task to do with preg_match.
Assume $array is the array that you begin with that has all the key=>val values.
foreach($fields as $key=>$val)
{
if(preg_match('/^custom_194_([0-9]+)$/', $key, $matches))
{
$num = $matches[1];
print "Key number $num has value $val\n";
}
}
The regular expression is ^custom_194_([0-9]+)$. The ^ means "beginning of the string." The $ means "end of the string." You can see that we explicitly spell out custom_194_. Then, we use ( and ) to identify a substring that we want to keep in the matches array. Inside ( and ), we look for the characters 0 through 9 using [0-9]. The + means "1 or more characters." So, we want 1 or more 0 through 9 characters.
The match array contains the entire string matched in the first index and then each sub-match in the remaining indexes. We only have one sub-match, which will be in index 1. So, $num is in $matches[1].

Finding the Index while searching from an Array using in_array in PHP

My aim is to find out what the operator is, and where it was in the original $operatorArray (which contains the various operators such as "+", "-" etc... )
So I have managed to check when $operator matches with another operator in my existing $operatorArray, however I need to know where in $operatorArray it is found.
foreach ($_SESSION['explodedQ'] as $operator){ //search through the user input for the operator.
if (in_array("$operator", $operatorArray)) { //if the operator that we found is in the array, then tell us what it is
print_r("$operator"); //prints the operator found
print_r("$positionNumber"); //prints where the operator is
} //if operator
else{
$positionNumber++; //The variable which keeps count on where the array is searching.
}
I've tried Google/Stack searching, but the thing is, I don't actually know what to Google search. I've searched for things like "find index from in_array" etc... and I can't see how to do it. If you could provide me with a simple way to understand how to achieve this, I would be greatful. Thanks for your time.
array_search will do what you are looking for
Taken straight from the PHP manual:
array_search() - Searches the array for a given value and returns the corresponding key if successful
If you're searching a non-associative array, it returns the corresponding key, which is the index you're looking for. For non-consecutively indexed arrays (i.e. array(1 => 'Foo', 3 => 'Bar', ...)) you can use the result of array_values() and search in it.
You might want to give this a try
foreach($_SESSION['explodedQ'] as $index => $operator) { /* your stuff */ }
That way you can print the $index as soon as your in_array() hits the right $operator.
i think you need array_search()
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
Use:
$key = array_search($operator, $array);

is it possible display multidemintional array in php using for loop

I have a multi-dimensional array like
Array
(
[0] => Array
(
[ename] => willy
[due_date] => 12:04:2011
[flag_code] => 0
)
[1] => Array
(
[Father] => Thomas
[due_date] => 13:04:2011
[flag_code] => 0
)
[2] => Array
(
[charges] => $49.00
)
)
i want to display values of array using php. but still fail. please any one help me to do this task....?
Since you're so adamant that this be accomplished using only for loops, I have to assume this is a homework question. Because of this, I'll point you to several PHP manual pages in the hopes that you'll review them and try to learn something for yourself:
Arrays
For Loops
Foreach Loops
Now, I'm going to break your actual question a few different questions:
Is it possible to display a multidimensional array using for loops?
Yes. It's entirely possible to use a for loop to iterate over a multidimensional array. You simply have to nest for loops inside for loops. i.e. you create a for loop to iterate over the outer array, then inside that loop you use another for loop to iterate over the inner array.
How can I iterate over a multidimensional array using a for loop?
Generally, when you use a for loop, the loop will look something like this:
for($i = 0; $i < $maxValue; $i++) {
// do something with $1
}
While this works well for indexed arrays (i.e. arrays with numeric keys), so long as they have sequential keys (i.e. keys which use each integer in order. for example, an array with keys 0, 1, and 2 is sequential; an array with keys 0, 2, and 3 is not because it jumps over 1), this doesn't work well for associative arrays (i.e arrays with text as keys - for example, $array = array("abc" = 123);) because these arrays won't have keys with the numerical indexes your for loop will produce.
Instead, you need to get a bit creative.
One way that you could do this is to use array_keys to get an indexed array of the keys your other array uses. For example, look at this simple, one-dimensional array:
$dinner = array(
"drink" => "water",
"meat" => "chicken",
"vegetable" => "corn"
);
This array has three elements, each with an associative key. We can get an indexed array of its keys using array_keys:
$keys = array_keys($dinner);
This will return the following:
Array
(
[0] => drink
[1] => meat
[2] => vegetable
)
Now, we can iterate over the keys, and use their values to access the associative keys in the original array:
for($i = 0; $i < count($keys); $i++) {
echo $dinner[$keys[$i]] . "";
}
As we iterate over this loop, the index $i will be set to hold each index of the $keys array. The associated element of this key will be the name of a key in the $dinner array. We then use this key name to access the $dinner array elements in order.
Alternatively, you could use a combination of the reset, current and next functions to iterate over the values in the array, for example:
for($element = current($dinner);
current($dinner) !== false;
$element = next($dinner)
) {
echo $element . "<br />";
}
In this loop, you initialize the $element variable to be the first element in the array using reset, which sets the array pointer to the first element, then returns that element. Next, we check the value of current($dinner) to ensure that there is a value to process. current() returns the value of the element the array pointer is currently set at, or false if there is no element there. Finally, at the end of the loop, we use next to set the array pointer ahead by one. next will return false when we try to read beyond the end of the array, but we ignore that and wait for current to notice that there is no current element to stop the loop.
Now, having written all of that, there really isn't any reason to do jump through all these hoops, since PHP has the built-in foreach construct which allows you to iterate over each of an arrays elements, regardless of key type:
foreach($dinner as $key => $value) {
echo "The element in key '" . $key . "' is '" . $value ."'. <br />";
}
This is why I'm assuming this is a homework assignment, since you would probably never have reason to jump through these hoops in a production environment. It is, however, good to know that such constructs exist. For example, if you could use any loop but a foreach, then it would be a lot simpler to just use a while loop than to try to bash a for loop into doing what you want:
reset($dinner);
while (list($key, $value) = each($dinner)) {
echo "The value of '" . $key . "' is '" . $value . "'.<br />";
}
In summary, to iterate over a multidimensional array with associative keys, you would need to nest loops inside each other as shown in the answer to the first question, using one of the loops shown in the answer to the second question to iterate over the associative key values. I'll leave the actual implementation as an exercise for the reader.
To print the values of a array, you can use the print_r function:
print_r($array);
This saves a for-loop.
Just use the handy function print_r
print_r($myarray);
If you don't want to use the print_r function, then for a true n-dimensional array solution:
function array_out($key, $value, $n) {
// Optional Indentation
for($i=0; $i < $n; $i++)
echo(" ");
if(!is_array($value)) {
echo($key . " => " . $value . "<br/>");
} else {
echo($key . " => <br/>");
foreach($value as $k => $v)
array_out($k, $v, $n+1);
}
}
array_out("MyArray", $myArray, 0);
Not sure if its possible to do with a for loop and mixed associative arrays, but foreach does work just fine.
If you have to do it with a for loop, you want the following:
$count = count($array)
for($i = 0; $i <= $count; $i++)
{
$count2=count($array[$i]);
for($j = 0; $j <= $count2; $j++)
{
print $array[$i][$j] . "<br/>";
}
}
foreach( $array as $row ) {
$values = array_values($row);
foreach( $values as $v ) {
echo "$v<br>";
}
}
Should output:
willy
12:04:2011
0
Thomas
13:04:2011
0
$49.00
This will actually be readable:
echo '<pre>';
print_r($myCoolArray);
echo '</pre>';
You would need to do it using something like assigning array_keys to an array, then using a for loop to go through that, etc...
But this is exactly why we have foreach - it would be quicker to write, read and run. Can you explain why it must be done with for?

How to remove all instances of duplicated values from an array

I know there is array_unique function, but I want to remove duplicates. Is there a built-in function or do I have to roll my own.
Example input:
banna, banna, mango, mango, apple
Expected output:
apple
You can use a combination of array_unique, array_diff_assoc and array_diff:
array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
You can use
$singleOccurences = array_keys(
array_filter(
array_count_values(
array('banana', 'mango', 'banana', 'mango', 'apple' )
),
function($val) {
return $val === 1;
}
)
)
See
array_count_values — Counts all the values of an array
array_filter — Filters elements of an array using a callback function
array_keys — Return all the keys or a subset of the keys of an array
callbacks
Just write your own simple foreach loop:
$used = array();
$array = array("banna","banna","mango","mango","apple");
foreach($array as $arrayKey => $arrayValue){
if(isset($used[$arrayValue])){
unset($array[$used[$arrayValue]]);
unset($array[$arrayKey]);
}
$used[$arrayValue] = $arrayKey;
}
var_dump($array); // array(1) { [4]=> string(5) "apple" }
have fun :)
If you want to only leave values in the array that are already unique, rather than select one unique instance of each value, you will indeed have to roll your own. Built in functionality is just there to sanitise value sets, rather than filter.
You want to remove any entries that have duplicates, so that you're left with only the entries that were unique in the list?
Hmm it does sound like something you'll need to roll your own.
There is no existing function; You'll have to do this in two passes, one to count the unique values and one to extract the unique values:
$count = array();
foreach ($values as $value) {
if (array_key_exists($value, $count))
++$count[$value];
else
$count[$value] = 1;
}
$unique = array();
foreach ($count as $value => $count) {
if ($count == 1)
$unique[] = $value;
}
The answer on top looks great, but on a side note: if you ever want to eliminate duplicates but leave the first one, using array_flip twice would be a pretty simple way to do so. array_flip(array_flip(x))
Only partially relevant to this specific question - but I created this function from Gumbo's answer for multi dimensional arrays:
function get_default($array)
{
$default = array_column($array, 'default', 'id');
$array = array_diff($default, array_diff_assoc($default, array_unique($default)));
return key($array);
}
In this example, I had cached statuses and each one other than the default was 0 (the default was 1). I index the default array from the IDs, and then turn it into a string. So to be clear - the returned result of this is the ID of the default status providing it's in the same part of the multi dimensional array and not the key of it
PHP.net http://php.net/manual/en/function.array-unique.php
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.
New solution:
function remove_dupes(array $array){
$ret_array = array();
foreach($array as $key => $val){
if(count(array_keys($val) > 1){
continue;
} else {
$ret_array[$key] = $val;
}
}

PHP - Getting the index of a element from a array

How can I get the current element number when I'm traversing a array?
I know about count(), but I was hoping there's a built-in function for getting the current field index too, without having to add a extra counter variable.
like this:
foreach($array as $key => value)
if(index($key) == count($array) ....
You should use the key() function.
key($array)
should return the current key.
If you need the position of the current key:
array_search($key, array_keys($array));
PHP arrays are both integer-indexed and string-indexed. You can even mix them:
array('red', 'green', 'white', 'color3'=>'blue', 3=>'yellow');
What do you want the index to be for the value 'blue'? Is it 3? But that's actually the index of the value 'yellow', so that would be an ambiguity.
Another solution for you is to coerce the array to an integer-indexed list of values.
foreach (array_values($array) as $i => $value) {
echo "$i: $value\n";
}
Output:
0: red
1: green
2: white
3: blue
4: yellow
foreach() {
$i++;
if(index($key) == $i){}
//
}
function Index($index) {
$Count = count($YOUR_ARRAY);
if ($index <= $Count) {
$Keys = array_keys($YOUR_ARRAY);
$Value = array_values($YOUR_ARRAY);
return $Keys[$index] . ' = ' . $Value[$index];
} else {
return "Out of the ring";
}
}
echo 'Index : ' . Index(0);
Replace the ( $YOUR_ARRAY )
I recently had to figure this out for myself and ended up on a solution inspired by #Zahymaka 's answer, but solving the 2x looping of the array.
What you can do is create an array with all your keys, in the order they exist, and then loop through that.
$keys=array_keys($items);
foreach($keys as $index=>$key){
echo "position: $index".PHP_EOL."item: ".PHP_EOL;
var_dump($items[$key]);
...
}
PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else
an array does not contain index when elements are associative. An array in php can contain mixed values like this:
$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");
print_r($var);
Gives you:
Array
(
[0] => apple
[1] => banana
[foo] => grape
[2] => carrot
[bar] => donkey
)
What are you trying to achieve since you need the index value in an associative array?
There is no way to get a position which you really want.
For associative array, to determine last iteration you can use already mentioned counter variable, or determine last item's key first:
end($array);
$last = key($array);
foreach($array as $key => value)
if($key == $last) ....

Categories