Struggling with a tiny problem.
I have an array:
Array
(
[0] =>
[6] => 6
[3] => 5
[2] => 7
)
I am chec
You could just use this http://www.php.net/manual/en/function.array-search.php
$key = array_search(5, $array)
if ($key !== false) {
...
Maybe you want to use array_search instead, which returns false if the value is not found and the index if the value is found. Check out the description here
In case anyone need it in array of arrrays. My case was this:
I had an array like this:
$myArray =
array:3 [▼
0 => array:3 [▼
0 => 2
1 => 0
2 => "2019-07-21 23:59:59"
]
1 => array:3 [▼
0 => 3
1 => 2
2 => "2019-07-21 23:59:59"
]
2 => array:3 [▼
0 => 1
1 => 1
2 => "2019-07-21 23:59:59"
]
]
And another one like this (an array of objects):
$Array2 =
Collection {#771 ▼
#items: array:12 [▼
0 => {#1047 ▼
+"id": 2
+"name": "demografico"
+"dict_key": "demographic"
+"component": "Demographic"
+"country_id": null
+"created_at": null
+"updated_at": null
}
1 => {#1041 ▶}
2 => {#1040 ▶}
etc...
As the OP, I had to "do something" (use values in a html php template, my case Laravel with blade) with the key where some value was in the array. For my code, I had to use this:
foreach($Array2 as $key => $item)
if(false !== $key = array_search($item->id, array_column($myArray, 0))
// Note that $key is overwritten
<input type="number" class="form-control" id="{!! $item->id !!}" value="{{ $myArray[$key][1] }}">
array_search() is what you are looking for.
if (false !== $key = array_search(5, $array)) {
//do something
} else {
// do something else
}
You can try
if(in_array(5, $array))
{
$key = array_search(5, $array);
echo $key;
}
this way you know it exists, and if it doesn't it doesn't cause notices, warnings, or fatal script errors depending on what your doing with that key there after.
If you only need the key of the first match, use array_search()
:
$key = array_search(5, $array);
if ($key !== false) {
// Found...
}
If you need the keys of all entries that match a specific value, use array_keys()
:
$keys = array_keys($array, 5);
if (count($keys) > 0) {
// At least one match...
}