1

The code below generates an associative array (key=>value), how can I have a non-associative array (e.g. just keys)? e.g. array('1','2','3','4','5');

$join_have = array();
$join_need = array();
array_push($join_have,$row2['id']);
array_push($join_need,$row3['id']);

I'm trying to construct two arrays to compare the database autoincrement id's for a JOIN table. The JOIN table is one of three (it allows unlimited number of associations instead of statically adding columns in the tables).

The point is to determine what JOIN table id's I have to keep, what I will DELETE and what I will INSERT for id's.

9
  • I am not sure what you mean. this will give you an array with starting index 0. what is it that you want? Commented Dec 13, 2011 at 20:23
  • 3
    Still do not understand what u need.... Commented Dec 13, 2011 at 20:24
  • 1
    Do you only want the arrays keys? If so, just use array_keys(). Commented Dec 13, 2011 at 20:31
  • 1
    Could you clarify the question? PHP arrays by definition always have both a key and value. Might also help if you show the value of $row2, the values you are getting now in $join_need, and what you'd like to see in $join_need instead. Commented Dec 13, 2011 at 20:33
  • 1
    As far as I understand the code, it generates a non-associative array. If you want just keys use array_keys(). Commented Dec 13, 2011 at 20:34

1 Answer 1

7

Arrays in php always have keys and values since it's very definition is an ordered map.

For example

$array = array(1, 2, 3, 4, 5);

Would have the following key, value pairs.

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

I think what you're asking is how do you set the keys in an array instead of the value.

You would simply do.

$join_have = array();
$join_have [ $row2['id'] ] = ''; 

This would still give you a key, value pair but you would be setting the key.

Sign up to request clarification or add additional context in comments.

4 Comments

array_flip on the original array will also do the job.
Yes, but why not construct it how you want in the first place, instead of constructing it then flipping it ?
I agree in the context of the question, but in general it seems like code smell.
warning: array_flip will destroy arrays with same values.

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.