user3106858
user3106858

Reputation: 35

Split a string into an array, and assign a value based on their letter?

I'm not asking you to code it for me or anything, snippets of code or just pointing me in the right direction will help me out a lot.

This is what I'm basically trying to do, you have the word "abcdefg"

I want it to split up the string into an array (or whatever works best?) , then assign a value based on what letter is stored into the array. (based on the alphabet , a = 1 , b = 2 , c = 3 , z = 26)

so abcdefg will turn into something like

$foo("a" => 1, "b" =>2, "c" => 3, etc..);

but obviously if "abcdefg" was "zaj", the array would be "z" => 26 , "a" => 1 , "j" => 10

Basically, convert a string of letters into their alphabetical num value sorta?

Upvotes: 1

Views: 303

Answers (2)

Steps that has been put to implement this.

  • Generate an alphabet array (alphabets starting from index 1)
  • Get the value which which you want to generate as an array.
  • Split them up with str_split
  • Using a foreach construct search them in the earlier alphabet array that was created using array_search
  • When found just , just grab their key and value and put it in the new array.

<?php
$alph[]='Start';
foreach(range('a','z') as $val)
{
    $alph[]=$val;
}

$makethisvalasarray='zaj';
$makethisvalasarray=str_split($makethisvalasarray);

foreach($makethisvalasarray as $val)
{
    $newarr[$val]=array_search($val,$alph);
}

print_r($newarr);

OUTPUT :

Array
(
    [z] => 26
    [a] => 1
    [j] => 10
)

Upvotes: 0

Conor McDermottroe
Conor McDermottroe

Reputation: 1363

The functions you need are:

With those functions you can solve this problem in a very small number of lines of code.

Upvotes: 1

Related Questions