1

How to avoid 34 overridden by 124 in the following PHP code? I just want to keep the 34 and 124 both.

$arr = array(12, 34, "df"=>43, "1"=>124, 65);
$num = count($arr);
reset($arr);
for ($i = 1; $i <= $num; ++$i) {
    echo 'The Current Position:' . key($arr);
    echo '<br />';
    echo 'The Current Value:'. current($arr);
    next($arr);
    echo '<br />';
    echo '<br />';
}
4
  • 1
    Just let PHP do the indexing. Commented May 7, 2016 at 3:18
  • you can remove the keys from the array. Commented May 7, 2016 at 3:18
  • 1
    @Rizier123 If I want to keep "1" as the key of 124, how to deal with it? Commented May 7, 2016 at 3:23
  • 1
    In the definition itself you can't do anything about it. You would have to check if the key already exist, before you overwrite it, Commented May 7, 2016 at 3:24

2 Answers 2

1

PHP will always treat all numeric keys as integers even if they are inside string variables or quotes.

The following can make it quite apparent:

<?php

$arr = [1 => 'hi', '2' => 'bye', 'a1' => 'hiha'];

var_export($arr);

The solution is to prefix the values that you don't want indexed as integers with a letter.

Note that mixing indexed and associative arrays indicates a serious lack of organization that you will regret later, if you don't already.

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

Comments

1

Your array indexing is not valid.

You need to design an array with unique keys, let PHP do the indexing. you can change the index "1" with "one" for unique key.

If you print_r your array then you must see the result like this

Array
(
    [0] => 12
    [1] => 124
    [df] => 43
    [2] => 65
)

So don't make an array with duplicate key, you might loss data.

$arr = array(12, 34, "df" => 43, "one" => 124, 65);
foreach($arr as $key => $val){
    echo $key." - ".$val."<br/>";
}

Result:

key - value
0   - 12
1   - 34
df  - 43
one - 124
2   - 65

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.