0

I have 2 arrays : 1 is all the alphabets and the other is a word which will be encrypted.

Problem : How can I have my program echo the array intersection but with the position of the intersection from the first array. So, I don't want "c" to have a position of 1 from the second array but rather a position of 3 in the first array.

PHP Code :

<?php

$cypher = $_POST['cypher_text'];
$array1 = array_merge(range('A', 'Z'), range('a', 'z'));
$array2 = str_split($cypher);
print_r($array1);
echo "<br/>";
print_r($array2);
echo "<br/>";
print_r(array_intersect_key($array2, $array1));

?>

Result of PHP program enter image description here

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • Change the order of arguments to `array_intersect`. – Barmar May 16 '17 at 20:06
  • Why are you using `array_intersect_key`? The keys of both arrays are just numbers starting from 0. – Barmar May 16 '17 at 20:10
  • Using `array_intersect` won't work if the cypher text contains any duplicate letters. The result will just contain one entry for all the duplicates. It seems like you're taking a totally wrong approach to solving this. – Barmar May 16 '17 at 20:12

1 Answers1

0

Use array_intersect rather than array_intersect_key, and switch the order of the arguments, because the result keeps the keys from the first argument.

print_r(array_intersect($array1, $array2));

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • The reason I have the arguments opposite to you is because I want the program to chronologically go through the word which has been put in to be cyphered. For example, I want the program to search for A first then T then T again and so on... I don't want it to go through the alphabet first so that I get it in the order --> a , c , k... Can I work around this problem in any way? – SIddharth M. May 16 '17 at 21:38
  • No matter what order you go in, you won't get any duplicates. All this does is find out the alphabetic positions of each letter in the cyphertext. You have to use a separate loop to go throught the cyphertext and replace them with the encoded value. – Barmar May 16 '17 at 21:40