0

I am calling a function like:

get(array('id_person' => $person, 'ot' => $ot  ));

In function How can I access the key and value as they are variable?

function get($where=array()) {

  echo where[0];
  echo where[1];
}

How to extract 'id_person' => $person, 'ot' => $ot without using foreach as I know how many key-values pairs I have inside function?

1
  • You need to elaborate on your usage and input variance. If you want to turn the array into an indexed version, use array_values() and then $where[0] etc. (= generally not advisable). Commented Mar 28, 2013 at 1:31

4 Answers 4

1

You can access them via $where['id_person'] / $where['ot'] if you know that they will always have these keys.

If you want to access the first and second element, you can do it like this

reset($where)
$first = current($where);
$second = next($where);
Sign up to request clarification or add additional context in comments.

6 Comments

so $where['id_person'] , where[0], $where['ot'], where[1] Is it correct
You always pass arrays that have the keys id_person and ot? Then you can do it this way
@cMinor - Your array is not numerically indexed, so you can't do $where[0]. You can only do $where['id_person'] to get the first element in the array.
In php array is actually a dictionary. If you don't specify names like id_person and ot, you can access things using the standard zero-based indexing, that's the default. But using key-value pairs is easier to understand in most cases.
so I understand to get value of 'id_person' I do $where['id_person'], but to know the string it self 'id_person'?
|
1

Couple ways. If you know what keys to expect, you can directly address $where['id_person']; Or you can extract them as local variables:

function get($where=array()) {
   extract($where);
   echo $id_person;
}

If you don't know what to expect, just loop through them:

foreach($where AS $key => $value) {
    echo "I found $key which is $value!";
}

3 Comments

If all of them can be variables, How would I access them, Is a foreach loop the only way out?
Not sure what you mean. If they are 'variable' in that you don't know what keys will be passed in, foreach is the best way to find out.
If you want to avoid foreach() so that you can restrict how many keys are allowed, just check that first. if(count($where) > 4) return "too many"; I still think you'll find foreach() the best way to figure out what keys you received.
0

Just do $where['id_person'] and $where['ot'] like you do in JavaScript.

Comments

0

If you do not care about keys and want to use array as ordered array you can shift it.

function get($where=array()) {
$value1 = array_shift($where);
$value2 = array_shift($where);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.