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) ....
Related
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
See this:
$q = 'blah';
for($k = 0; $k < count($results_array); $k++){
$results_array_ . $k = explode(',', $results_array[$k]);
foreach($results_array_ . $k as $key => $value){
if (stripos($value, $q) === false) {
unset($results_array_ . $k[$key]);
break;
}
}
}
On line 3 I'm simply using "$results_array_ . $k" and it's working just fine, but on line 6 I'm getting PHP parse errors on "unset($results_array_ . $k[$key])", why is this happening?
I appreciate anykind of help
Why I'm doing it:
I have an array named results_array:
var_dump($results_array):
0 => php,mysql,jquery,ruby,html,css,lamp
1 => mouse,keyboard,laptop,pad
2 => table,sofa,caption
and I have a $q which stands for query, I want to search in the $results_array and remove the items which has nothing to do with the query, so if I set $q=a then results array should be this:
0 => lamp
1 => keyboard,laptop,pad
3 => table,sofa,caption
now, I want to put the above results in each index of the results_array, at the end results_array should be:
0 => lamp
1 => keyboard
2 => laptop
3 => pad
4 => table
5 => sofa
6 => caption
Answer to original question
unset expects its argument to be a direct reference to a value, e.g. $var or $array['key']. If you want to dynamically create the argument based on other values, you 'll have to use variable variable syntax:
unset(${$results_array_ . $k[$key]});
This will get rid of the warning, but it still won't make the code work because it's fundamentally flawed. Line 3 which you mention reads:
$results_array_ . $k = explode(',', $results_array[$k]);
What this does is explode an array into $k and then concatenate $results_array_ with $k and... throw away the result. You could just as easily have written
$k = explode(',', $results_array[$k]);
and it would work the same (except possibly not giving an E_NOTICE that $_results_array_ does not exist).
So, it seems that you have a misunderstanding of how some PHP fundamentals work. It would be best if you asked another question that explains what you are trying to do, in order to determine what would be a good way of doing it.
Answer to current question
Let's take the steps one at a time:
Take the array of strings and turn each string into an array with explode, making an array of arrays. You can do this with array_map or a simple foreach.
"Flatten" the array of arrays into one big array. You can do this with array_merge or array_merge_recursive (the details will be a bit different, the idea is the same).
Search the flattened array and filter out uninteresting elements with array_filter.
If necessary, reindex the filtered array so that it has consecutive numeric keys with array_values.
Here's code that does this, albeit a little differently (I am doing steps 1 and 2 at the same time in the first line using array_reduce):
$array = (...);
$array = array_reduce($array, function(&$result, $item) {
return array_merge($result, explode(',', $item));
}, array());
$array = array_filter($array, function($item) use ($string) {
return strpos($item, $string) !== false;
});
$result = array_values($array);
A version that does the same without using fancy functions:
// Step 1
foreach($array as &$row) {
$row = explode(',', $row);
}
unset($row);
// Step 2
$array = call_user_func_array('array_merge_recursive', $array);
// Step 3
foreach ($array as $k => $v) {
if(strpos($v, 'a') === false) unset($array[$k]);
}
// Step 4
$array = array_values($array);
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?
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;
}
}
If I had an array like:
$array['foo'] = 400;
$array['bar'] = 'xyz';
And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?
reset() gives you the first value of the array if you have an element inside the array:
$value = reset($array);
It also gives you FALSE in case the array is empty.
PHP < 7.3
If you don't know enough about the array (you're not sure whether the first key is foo or bar) then the array might well also be, maybe, empty.
So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:
$value = empty($arr) ? $default : reset($arr);
The above code uses reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:
$value = $default;
foreach(array_slice($arr, 0, 1) as $value);
Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:
foreach(array_slice($arr, 0, 1, true) as $key => $value);
To get the first item as a pair (key => value):
$item = array_slice($arr, 0, 1, true);
Simple modification to get the last item, key and value separately:
foreach(array_slice($arr, -1, 1, true) as $key => $value);
performance
If the array is not really big, you don't actually need array_slice and can rather get a copy of the whole keys array, then get the first item:
$key = count($arr) ? array_keys($arr)[0] : null;
If you have a very big array, though, the call to array_keys will require significant time and memory more than array_slice (both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).
A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.
PHP 7.3+
PHP 7.3 onwards implements array_key_first() as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.
So since PHP 7.3 the first value of $array may be accessed with
$array[array_key_first($array)];
You still had better check that the array is not empty though, or you will get an error:
$firstKey = array_key_first($array);
if (null === $firstKey) {
$value = "Array is empty"; // An error should be handled here
} else {
$value = $array[$firstKey];
}
Fake loop that breaks on the first iteration:
$key = $value = NULL;
foreach ($array as $key => $value) {
break;
}
echo "$key = $value\n";
Or use each() (warning: deprecated as of PHP 7.2.0):
reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.
$first = array_shift($array);
current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.
$first = current($array);
If you want to make sure that it is pointing to the first element, you can always use reset().
reset($array);
$first = current($array);
another easy and simple way to do it use array_values
array_values($array)[0]
Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:
$arr = array(1,2);
current($arr); // 1
next($arr); // 2
current($arr); // 2
reset($arr); // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.
The way to do this without changing the pointer:
$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));
The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
if(is_array($array))
{
reset($array);
$first = key($array);
}
We can do
$first = reset($array);
Instead of
reset($array);
$first = current($array);
As reset()
returns the first element of the array after reset;
You can make:
$values = array_values($array);
echo $values[0];
Use reset() function to get the first item out of that array without knowing the key for it like this.
$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);
output //
400
Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:
$first = $array[array_key_first($array)];
More likely, you'll want to handle the case where the array is empty:
$first = (empty($array)) ? $default : $array[array_key_first($array)];
You can try this.
To get first value of the array :-
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
var_dump(current($large_array));
?>
To get the first key of the array
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
$large_array_keys = array_keys($large_array);
var_dump(array_shift($large_array_keys));
?>
In one line:
$array['foo'] = 400;
$array['bar'] = 'xyz';
echo 'First value= ' . $array[array_keys($array)[0]];
Expanded:
$keys = array_keys($array);
$key = $keys[0];
$value = $array[$key];
echo 'First value = ' . $value;
You could use array_values
$firstValue = array_values($array)[0];
You could use array_shift
I do this to get the first and last value. This works with more values too.
$a = array(
'foo' => 400,
'bar' => 'xyz',
);
$first = current($a); //400
$last = end($a); //xyz