RhymeGuy
RhymeGuy

Reputation: 2112

PHP search array using wildcard?

Assume that i have the following arrays containing:

Array (
     [0] => 099/3274-6974
     [1] => 099/12-365898
     [2] => 001/323-9139
     [3] => 002/3274-6974
     [4] => 000/3623-8888
     [5] => 001/323-9139
     [6] => www.somesite.com
)

Where:

I need to convert given array into 3 new arrays, each containing proper information, like arrayTelephone, arrayMobile, arraySite.

Function in_array works only if i know whole value of key in the given array, which is not my case.

Upvotes: 2

Views: 1649

Answers (4)

jsonx
jsonx

Reputation: 1090

Yes i actually wrote the full code with preg_match but after reading some comments i accept that its better to show the way.

You will create three different arrays named arrayTelephone, arrayMobile, arraySite.

than you will search though your first array with foreach or for loop. Compare your current loop value with your criteria and push the value to one of the convenient new arrays (arrayTelephone, arrayMobile, arraySite) after pushing just continue your loop with "continue" statement.

You can find the solution by looking add the Perfect PHP Guide

Upvotes: 0

ilanco
ilanco

Reputation: 9957

You can loop over the array and push the value to the correct new array based on your criteria. Example:

<?php

$fixed_array = array();

foreach ($data_array as $data) {
    if (strpos($data, '099') === 0) {
        $fixed_array[] = $data;
    }

    if ....
}

Upvotes: 1

Ry-
Ry-

Reputation: 224942

Loop through all the items and sort them into the appropriate arrays based on the first 4 characters.

$arrayTelephone = array();
$arrayMobile = array();
$arraySite = array();

foreach($data as $item) {
    switch(substr($item, 0, 4)) {
        case '000/':
        case '001/':
        case '002/':
            $arrayMobile[] = $item;
            break;
        case '099/':
            $arrayTelephone[] = $item;
            break;
        case 'www.':
            $arraySite[] = $item;
            break;
    }
}

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

Create the three empty arrays, loop through the source array with foreach, inspect each value (regexp is nice for this) and add the items to their respective arrays.

Upvotes: 2

Related Questions