0

I have an array with some repeating string values. How to replace these string values (as a whole, because some words are repeated in others strings) with corresponding specific numeric values, as bellow?

deloc        = 1
foarte puţin = 2
mediu        = 3
mult         = 4
foarte mult  = 5

This is the array (example):

array = (
    "tensionat"     => "mediu",
    "trist"         => "mult",
    "melancolic"    => "deloc",
    "fara_speranta" => "foarte puțin",
    "nefolositor"]  => "deloc",
    "ingrijorat"    => "foarte mult",
    "amarat"        => "deloc",
    "anxios"        => "mediu"
);

How can this

1 Answer 1

1

Try this

$data = array (
    "tensionat"     => "mediu",
    "trist"         => "mult",
    "melancolic"    => "deloc",
    "fara_speranta" => "foarte puțin",
    "nefolositor"   => "deloc",
    "ingrijorat"    => "foarte mult",
    "amarat"        => "deloc",
    "anxios"        => "mediu"
);

$repl = array (
    'deloc'        => 1,
    'foarte puţin' => 2,
    'mediu'        => 3,
    'mult'         => 4,
    'foarte mult'  => 5,
);

$result = array ();

foreach ($data as $key => $value) {
    $result[$key] = !empty($repl[$value]) ? $repl[$value] : $value;
}

print_r($result);

Output:

Array
(
    [tensionat] => 3
    [trist] => 4
    [melancolic] => 1
    [fara_speranta] => foarte puțin
    [nefolositor] => 1
    [ingrijorat] => 5
    [amarat] => 1
    [anxios] => 3
)
Sign up to request clarification or add additional context in comments.

7 Comments

Note, foarte puţin !== foarte puțin.
Or in one line: $result = array_map(fn($v) => $repl[$v] ?? false ?: $v, $data);
@pilan, I got this error: syntax error, unexpected '=>'. What this can be?
Can you use "fara_speranta" => "foarte puţin", instead of "fara_speranta" => "foarte puțin", or 'foarte puțin' => 2, instead of 'foarte puţin' => 2,? foarte puţin is NOT equal to foarte puțin! Due to these both ţ and ț are different.
Why do you use the different strings?
|

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.