For instance, in the following code, how to get the position -order- of a given element inside the array:
<?php
$cars=array("Volvo","BMW","Toyota","Tesla","Volkswagen");
//for Volvo, an echo statement should return 1
//for BMW, an echo statement should return 2
//for Toyota, an echo statement should return 3 ... and so on ...
?>
Update: After receiving some useful contributions regarding the implementation of search_array()
, I was wondering if I can apply the same for arrays contained inside another array. vardump()
for a multidimensional array shows me the following:
array (size=3)
'home' =>
array (size=6)
'label' =>
object(MagentoFrameworkPhrase)[5814]
private 'text' => string 'Home' (length=4)
private 'arguments' =>
array (size=0)
...
'title' =>
object(MagentoFrameworkPhrase)[5815]
private 'text' => string 'Go to Home Page' (length=15)
private 'arguments' =>
array (size=0)
...
'link' => string 'http://example.com/example.html' (length=23)
'first' => boolean true
'last' => null
'readonly' => null
'category4' =>
array (size=6)
'label' => string 'Transport' (length=9)
'link' => string 'http://example.com/example.html' (length=23)
'title' => null
'first' => null
'last' => null
'readonly' => null
'category686' =>
array (size=6)
'label' => string 'Transport' (length=15)
'link' => string '' (length=0)
'title' => null
'first' => null
'last' => boolean true
'readonly' => null
How to get in this case the position of category4 in regard to the array of size=3
?
3
Answers
array_search()
will let you find the position of an element or it returns FALSE if the element was not found. Read more about it at http://php.net/manual/en/function.array-search.phpFrom the documentation, this is what can be returned from this function:
And here is an example:
As the example is very simple, meaning, is just an array of strings, then you may use array_flip, which is going to return an array that flips the keys with the values, so we can do:
Also remember that the array start with
0
and not with1
, then the index of “Volvo” is0
and not1
.Yes you can use array_search(), but array_search() returns the index of the element which is start from 0, so you can do like below,
this is your array
$cars=array("Volvo","BMW","Toyota","Tesla","Volkswagen");
echo (array_search("Volvo",$cars)) + 1; //you can getting 1 as output